简体   繁体   中英

Translating a Unity 2D Code into 3D

I got a small Script for a swinging Axe in 2D. Just like for example this one here:

Dark Souls Swinging Axe

My problem is, that I do not know how to translate the 2D code into 3D. My object got a Rigidbody and a Hinge Joint (for swinging Physics) attached. The

Rigidbody.angularVelocity

needs to get a Vector3 instead of a float value.

My Code:

   Rigidbody rigid;
    float rangeToPush = 0.3f;
    float velocity = 120;

    private void Start()
    {
        rigid = GetComponent<Rigidbody>();
        rigid.angularVelocity = Vector3.down * velocity;
    }

    private void Update()
    {
        if (transform.rotation.z > 0 &&
            transform.rotation.z < -rangeToPush &&
            rigid.angularVelocity.magnitude > 0 &&
            rigid.angularVelocity.magnitude < velocity)
        {
            rigid.angularVelocity = Vector3.down * velocity;
        }

        else if (transform.rotation.z < 0 &&
            transform.rotation.z > rangeToPush &&
            rigid.angularVelocity.magnitude < 0 &&
            rigid.angularVelocity.magnitude > -120)
        {
            rigid.angularVelocity = Vector3.down * -velocity;
        }
    }

The things missing are the value for

data.Rigid.angularVelocity = ?Vector3?

instead of my float value and obviously my two last if-statements are wrong, i have

if( /* the other statements .. && */ data.Rigid.angularVelocity > 0 && data.Rigid.angularVelocity < data.RigidVelocity)

and I need to convert it into 3D.

Thanks a lot for help!

Edit: I tried to use

data.Rigid.angularVelocity = Vector3.down * data.RigidVelocity;

and for my if-statements

Rigid.angularVelocity.magnitude

but this is gonna swing for a limited time, not endless. So maybe I have to change a value in the Data Script or I have to use something else instead of magnitude ... I do not know

i finally got it. I removed the HingeJoint and used this code to make it swing endless:

    float speed = 0.4f; // Speed
    float amplitude = 70; // How far can it swing?

    private void Update()
    {
        transform.rotation = Quaternion.Euler(new Vector3(0, 0, Mathf.Sin(Time.timeSinceLevelLoad * Mathf.PI * speed) * amplitude)); // Swing
    }

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