Scripting – Top-Down Movement
•
Example 7: Player Movement based on Mouse Position
public class SpaceshipMovement : MonoBehaviour{
public float moveForce = 3;
public float minMouseDistance = 50;
private Rigidbody2D rigidBody;
private void Start(){
rigidBody = GetComponent<Rigidbody2D>();
}
private void FixedUpdate(){
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector2 mouseDirection = Input.mousePosition -
Camera.main.WorldToScreenPoint(transform.position);
if (mouseDirection.magnitude > minMouseDistance){
float rotationAngle = Mathf.Atan2(mouseDirection.normalized.y,
mouseDirection.normalized.x) * Mathf.Rad2Deg;
rigidBody.SetRotation(rotationAngle - 90);
}
rigidBody.velocity = (((transform.up * verticalInput) +
(transform.right * horizontalInput)) * moveForce);
}
}