Search code examples
c#unity-game-engineinputkeyboardtop-down

Unity - Make player point toward mouse


Im making a top-down shooter, where the player moves up, down, left, and right with WASD and constantly points toward the mouse. I want the movement to be irrelevant to the direction the player is pointing, but right now thats not the case.

Here is my code:

void Update() 
{
  float igarH = Input.GetAxisRaw("Horizontal");
  float igarV = Input.GetAxisRaw("Vertical");
  if (igarH > 0.5f || igarH < -0.5f) 
  {
    transform.Translate(new Vector3(igarH * moveSpeed * Time.deltaTime, 0f, 0f));
  }
  if (igarV > 0.5f || igarV < -0.5f)
  {
    transform.Translate(new Vector3(0f, igarV * moveSpeed * Time.deltaTime, 0f));
  }

  // Point toward mouse
  Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
  float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
  Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
  transform.rotation = rotation;
}

Sorry about the bad indentation, its kind of hard to figure out how the site wants me to do the markup, and I'm new to this site.

Why is the player moving differently based on where my mouse is? I want movement to be the same no matter what.

Please keep all answers related to Unity2D and not 3D, please.


Solution

  • Transform.Translate has an optional parameter relativeTo, in that you choose if you want the object to move relative to its own corrdinate system or the world coordinate system.

    Just change your calls to:

    if (igarH > 0.5f || igarH < -0.5f) {
      transform.Translate(new Vector3(igarH * moveSpeed * Time.deltaTime, 0f, 0f), Space.World);
    }
    if (igarV > 0.5f || igarV < -0.5f) {
      transform.Translate(new Vector3(0f, igarV * moveSpeed * Time.deltaTime, 0f), Space.World);
    }