2017-12-03 30 views
-1

개체가 특정 속도로 움직이는 프로그램을 작성하려고합니다. Java에는 방향을 결정하는 함수가 내장되어 있지 않습니다. Java에서 스크래치 코드를 어떻게 작성할 수 있습니까? 또한 객체가 다른 객체를 가리 키도록하는 방법이 있습니까?
Screenshot of Scratch code to make object move in a direction or point toward mouse
내가 코드는 다음과 같이 할 : 또한Java의 스크래치 기반 이동

public void move(int direction, int distance) { 
    // 0 degrees is up, 90 is right, 180 is down, 270 is left. 
} 

을 당신이 질문을 할 수있는 더 좋은 방법이 생각한다면, 나에게 팁을주지하시기 바랍니다, 이쪽은 내 첫 번째 질문은이 사이트에 .

+2

한 단어 : 삼각법. 첫 번째 질문은'sin'과'cos'를보고, 두 번째 질문은'arctan '을보십시오. –

+0

나는 삼각법과 관련이 있다는 것을 알고 있지만, 나의 구체적인 경우는 그것보다 조금 더 복잡하다. 좀 더 구체적으로 질문을 편집했습니다. –

답변

0

음, 지오메트리에 능숙한 친구와 함께 알아 냈습니다.

// Movement 
public void move(int speed) { 
    x += speed * Math.cos(direction * Math.PI/180); 
    y += speed * Math.sin(direction * Math.PI/180); 
} 
// Pointing toward an object 
public void pointToward(SObject target) { 
    direction = Math.atan2(target.y - y, target.x - x) * (180/Math.PI); 
} 
// Pointing toward the mouse 
public void pointTowardMouse() { 
    direction = Math.atan2(Main.mouse.getY() - y, Main.mouse.getX() - x) * (180/Math.PI); 
} 
// Ensure that the degrees of rotation stay between 0 and 359 
public void turn(int degrees) { 
    double newDir = direction; 
    newDir += degrees; 
    if (degrees > 0) { 
     if (newDir > 359) { 
      newDir -= 360; 
     } 
    } else if (degrees < 0) { 
     if (newDir < 0) { 
      newDir += 360; 
     } 
    } 
    direction = newDir; 
} 

나는이 자신의 게임에서 회전 운동을 필요로 다른 사람을 도울 수있는 것 같아요 : 이 우리와 함께 제공되는 기능은 다음과 같습니다.