Silverback9

#야생으로

Creative Coding 독학 제184일 2024년09월27일(금)

오늘은 MouseConstraint의 사용을 본격적으로 코딩해 보겠습니다~~^^*

MouseConstraint 객체를 생성하여, 변수 mConstraint에 저장하고, 다시 이 mConstraint를 engine.world의 구성요소로 더하겠습니다~~^^*

const {
    Engine,
    World,
    Bodies,
    Composite,
    Constraint,
    Mouse,
    MouseConstraint
} = Matter;


let engine;
let world;
let mConstraint;

 mConstraint = MouseConstraint.create(engine, options);
 World.add(world, mConstraint)

우리가 mouse로 어떤 물체를 클릭하게 되면 mConstraint의 body의 진리값이 true가 되어요~^^*

mouse가 동그라미 중 하나를 클릭하면~~^^* 다시 말해서, mConstraint의 body의 진리값이 true이면~~^^*

마우스로 동그라미를 움직이는 작업을 하면 될 것 같아요~~^^*

  if (mConstraint.body) {
   .
   .
   .
  }

마우스가 동그라미를 클릭하는 정확한 위치를 표현하기 위해서~

(1) 물체의 위치 좌표를 확인하고~~ 네~~ matter.js의 위치 좌표는 물체의 중심을 나타내고 있지요~~^^*?

 let pos = mConstraint.body.position;

(2) 물체의 중심에서의 마우스 클릭의 상대 위치 좌표를 확인하고~~

  let offset = mConstraint.constraint.pointB;
//pointB는 물체 중심을 기준으로 한 상대좌표 체계 위의 mouse 클릭 위치좌표입니다~~^^*

(3) 물체 위치 좌표에 마우스 상대 위치 좌표를 더하면~ Canvas 위의 마우스 클릭 좌표가 나오겠네요~~^^*

pos.x + offset.x
pos.y + offset.y

(4) 지속적으로 변화하는 마우스 움직임 좌표는 변수 m에 저장해 보겠습니다~

 let m = mConstraint.mouse.position;

(5) 물체를 클릭하여 조종하는 마우스의 움직임을 시각적으로 표현해 볼게요. mouse 클릭 좌표와 드래그 중인 mouse 위치 좌표를 서로 연결해 볼까요~^^*

 stroke(0, 255, 0);
 line(pos.x + offset.x, pos.y + offset.y, m.x, m.y);


마우스로 동그라미를 움직이는 작업 전체 지시문을 정리해 보겠습니다~

 if (mConstraint.body) {
        let pos = mConstraint.body.position;
        let offset = mConstraint.constraint.pointB;
        let m = mConstraint.mouse.position;
        stroke(0, 255, 0);
        line(pos.x + offset.x, pos.y + offset.y, m.x, m.y);
    }

어느덧 마우스로 동그라미를 클릭 드래그하여 동그라미의 움직임을 조종하는 핵심 코드들이 다 준비가 되었네요~^^*

그럼 우리~~^^* 전체 코드 함께 살펴 볼까요~~^^*

<!DOCTYPE html>
<html lang="en">
  <head>
    https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js
    https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/addons/p5.sound.min.js
    https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.min.js
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta charset="utf-8" />

  </head>
  <body>
    <main>
    </main>
    http://sketch.js
    http://circle.js
    http://boundary.js
  </body>
</html>
class Boundary {
    constructor(x, y, w, h, a) {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        let options = {
            friction: 0,
            restitution: 0.6,
            angle: a,
            isStatic: true
        }
        this.body = Bodies.rectangle(this.x, this.y, this.w, this.h, options);
        Composite.add(world, this.body);
    }

    show() {
        let pos = this.body.position;
        let angle = this.body.angle;
        push();
        translate(pos.x, pos.y);
        rotate(angle);
        rectMode(CENTER);
        noStroke();
        fill(0);
        rect(0, 0, this.w, this.h);
        pop();
    }
}
class Particle{
    constructor(x, y, r, fixed) {
        this.x = x;
        this.y = y;
        this.r = r;
        let options = {
            friction: 0,
            restitution: 0.95,
            isStatic: fixed
        }
        this.body = Bodies.circle(this.x, this.y, this.r,  options);
        Composite.add(world, this.body);
    }

    show() {
        let pos = this.body.position;
        let angle = this.body.angle;
        push();
        translate(pos.x, pos.y);
        rotate(angle);
        rectMode(CENTER);
        strokeWeight(1);
        stroke(255)
        fill(127);
        ellipse(0, 0, this.r*2);
        line(0,0,this.r,0);
        pop();
    }
}
const {
    Engine,
    World,
    Bodies,
    Composite,
    Constraint,
    Mouse,
    MouseConstraint
} = Matter;


let engine;
let world;
let particles = [];
let boundaries = [];
let mConstraint;

function setup() {
    let canvas = createCanvas(400, 400);
    engine = Engine.create();
    world = engine.world;
    
    let prev = null;
    for (let x = 200; x < 400; x += 20) {
        let fixed = false;
        if (!prev) {
            fixed = true;
        }
        let p = new Particle(x, 100, 10, fixed);
        particles.push(p);
        
        if (prev) {
            fixed = true;
            let options = {
                bodyA: p.body,
                bodyB: prev.body,
                length: 20,
                stiffness: 0.4
            }

            let constraint = Constraint.create(options);
            World.add(world, constraint);
        }
        prev = p;
    }
    boundaries.push(new Boundary(width / 2, 400, width, 20, 0));

    let canvasMouse = Mouse.create(canvas.elt);
    let options = {
        mouse: canvasMouse,
    }

    canvasMouse.pixelRatio = pixelDensity();
    mConstraint = MouseConstraint.create(engine, options);
    World.add(world, mConstraint);
}

function draw() {
    background(51);
    Engine.update(engine);
    for (let i = 0; i < boundaries.length; i++) {
        boundaries[i].show();
    }
    for (i = 0; i < particles.length; i++) {
        particles[i].show();
    }
    if (mConstraint.body) {
        let pos = mConstraint.body.position;
        let offset = mConstraint.constraint.pointB;
        let m = mConstraint.mouse.position;
        stroke(0, 255, 0);
        line(pos.x + offset.x, pos.y + offset.y, m.x, m.y);
    }
}

오~~~마우스로 동그라미 하나를 클릭하여 주욱 당기며 사슬의 대형 변화 뿐만 아니라 동그라미들의 회전각 운동도 함께 관찰해 보실까요~~^^*

네~~^^* Mouse Counstraint도 이제 마무리를 하였네요, 우리가~~^^*

내용 복습으로 동영상 강의를 우리 함께 보면 어떨까요~^^*

마우스가 대형을 조종하는 아주 큰 일을 하네요~~^^*

사람의 손가락 역할을 하는 자신만의 길을 충실히 가고 있는 우리들의 Mouse!

몸이 작고 가벼워 물 위에 쉽게 떠오르며 삶의 바다를 잘 헤엄치는 우리들의 Mouse!

우리들의 친구 Mouse와 함께 0과 1이 물결치는 컴퓨터의 바다를 즐겁게 헤엄칩시다~^^*

오늘도 저와 함께 코딩공부 해주셔서 감사합니다~~^^*

내일 우리 또 만나서, 함께 코딩공부 할까요~^^* matter.js를 좀더 알아가 봐요, 우리~~^^*

네~~!!! 꿈은 이루어 집니다~~~!!!

댓글 남기기