2017-12-03 8 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

1語:三角法。最初の質問は '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; 
} 

: これらは、私たちが思いついた機能です。

関連する問題