1

I am making a top down game on Unity, so I am using the x and z axis as my plane. I have my character rotated x 90, y 0, z 0 so that it is flat on the plane. As soon as I hit play the character is rotated vertical?! I think it has something to do with my script to face the mouse position.

What it should look like:

enter image description here

When I hit play:

enter image description here

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public static float moveSpeed = 10f;

    private Rigidbody rb;

    private Vector3 moveInput;
    private Vector3 moveVelocity;

    // Update is called once per frame

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        mainCamera = FindObjectOfType<Camera>();
    }

    void Update()
    {
        // Setting up movement along x and z axis. (Top Down Shooter)
        moveInput = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
        moveVelocity = moveInput * moveSpeed;

        //Make character look at mouse.
        var dir = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
        var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.AngleAxis(angle, Vector3.up);
    }

    void FixedUpdate()
    {   
        // Allows character to move.
        rb.velocity = moveVelocity;
    }
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Alex I
  • 41
  • 3
  • Possible duplicate of [Unity - Gameobject look at mouse](https://stackoverflow.com/questions/36615476/unity-gameobject-look-at-mouse) – Ahmed Ali Nov 14 '19 at 05:54
  • 1
    Well probably because you set a new rotation in `Update` .. re-check the calculation and your objects original orientation .. you might want to take it into account: `private Quaternion originalRotation;` then store it once `void Start(){ originalRotation = transform.rotation;}` then later use it like `transform.rotation = originalRotation * Quaternion.AngleAxis(...);` – derHugo Nov 14 '19 at 06:04
  • as i remember correctly in a 2D Game you need rotation around z instead of y, so instead of Vector3.up try a Vector3.forward. – Exar666Kun Nov 14 '19 at 06:09

1 Answers1

3

Figured it out: I am answering my own question to help others.

Vector3 difference = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position); 
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg; 
transform.rotation = Quaternion.Euler(90f, 0f, rotZ -90);

This does EXACTLY what I wanted!

Mukul Varshney
  • 3,131
  • 1
  • 12
  • 19
Alex I
  • 41
  • 3