Alex I
Alex I

Reputation: 41

When I hit play, my Sprite character rotates. Why?

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;
    }
}

Upvotes: 1

Views: 273

Answers (1)

Alex I
Alex I

Reputation: 41

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!

Upvotes: 3

Related Questions