How to stop body from rotating around wrong axis in unity

51 views Asked by At

I recently started on unity and I wanted to make simple movement which can be seen below.

using System.Collections.Generic;
using UnityEngine;

public class movement : MonoBehaviour
{
    //Variables
    float speed = 5.0f;
    public float turnSpeed = 4.0f;
    public float moveSpeed = 2.0f;
    public float minTurnAngle = -90.0f;
    public float maxTurnAngle = 90.0f;
    private float rotX;

    //Other
    Vector3 Char_velocity;
    Rigidbody Physics;

    void Start()
    {
        Physics = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        //Get axis on which we want to move
        if (Input.GetButton("Vertical"))
        {
            //Creating vector which velocity is calculated based on vect3, speed and gets FPS compensation via fixed 
            //delta time
            Char_velocity = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
            Physics.MovePosition(transform.position + Char_velocity * speed * Time.fixedDeltaTime);
        }
        
        if (Input.GetButton("Horizontal"))
        {
            Char_velocity = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
            Physics.MovePosition(transform.position + Char_velocity * speed * Time.deltaTime);
        }

        float y = Input.GetAxis("Mouse X") * turnSpeed;
        rotX += Input.GetAxis("Mouse Y") * turnSpeed;
        rotX = Mathf.Clamp(rotX, minTurnAngle, maxTurnAngle);
        transform.eulerAngles = new Vector2(-rotX, transform.eulerAngles.y + y);
    }
}

Mouse movement has been the problem for me. I got it to somewhat work but I have 2 issues. The camera should move the whole body while rotating from side to side but instead rotates the body when moving along the Y axis.

0

There are 0 answers