简体   繁体   中英

How do I get the z rotation of my object as a public float?

I have tried different ways of getting the z rotation of my object as a public float but i keep getting errors when i make it a public variable.

i have tried using quanternion and transform.

using UnityEngine;

public class PointerController : MonoBehaviour
{
    public float speed = 5f;

    private void Update()
    {
        rotate();
        calculate();
    }

    private void rotate()
    {
        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 = Quaternion.Slerp(transform.rotation, rotation, speed * Time.deltaTime);
    }

    public void calculate()
    {

    }
}

This part of the code is what i use to rotate my character to follow my mouse but i want to get a public variable saying the z rotation in the calculate method.

For example:

using UnityEngine;

public class PointerController : MonoBehaviour
{
    public float speed = 5f;
    public float z_rotation; //THIS LINE

    private void Update()
    {
        rotate();
        calculate();
    }

    private void rotate()
    {
        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 = Quaternion.Slerp(transform.rotation, rotation, speed * Time.deltaTime);
        z_rotation = transform.rotation.z; //AND THIS ONE
    }

    public void calculate()
    {

    }
}

Another example:

  using UnityEngine;

    public class PointerController : MonoBehaviour
    {
        public float speed = 5f;

        private void Update()
        {
            rotate();
            calculate(transform.rotation.z);
        }

        private void rotate()
        {
            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 = Quaternion.Slerp(transform.rotation, rotation, speed * Time.deltaTime);
        }

        public void calculate(float z_rotation)
        {

        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM