About AddFors for Unity

Asked 1 years ago, Updated 1 years ago, 39 views

Currently, I am thinking of creating a process in which characters move freely in 3D space, but when I do the following process, when I press W+A and S+D at the same time, it moves in a strange direction."W+A" moves to the upper left to the upper right, and "S+D" moves to the lower right to the lower left.
If anyone knows why, please let me know.

public class WalkAnimation:MonoBehavior
{
    private animator anm;
    private Rigidbody rb;
    private Vector 3 latestPos;

    void Start()
    {
        anm=GetComponent<Animator>();
        rb = GetComponent <Rigidbody >();
    }

    void Update()
    {
        if(Input.GetKey(KeyCode.W))
        {
            OnAnimator (-100);
        }
        else if (Input.GetKey(KeyCode.S))
        {
            OnAnimator (100);
        }
        else if (Input.GetKey(KeyCode.A))
        {
            OnAnimator (100);
        }
        else if (Input.GetKey(KeyCode.D))
        {
            OnAnimator (-100);
        }
        else
        {
            OffAnimator();
        }
    }

    private void OnAnimator (intwalk)
    {
        anm.SetBool("Walk", true);
        Vector3 diff = transform.position-latestPos;
        latestPos = transform.position;

        if (diff.magnitude>0.01f)
        {
            transform.rotation=Quaternion.LookRotation(diff);
        }

        if(Input.GetKey(KeyCode.W)||Input.GetKey(KeyCode.S))
        {
            rb.AddForce(0,0,walk,ForceMode.Force);
        }
        if(Input.GetKey(KeyCode.A)||Input.GetKey(KeyCode.D))
        {
            rb.AddForce (walk, 0, 0, ForceMode.Force);
        }
    }

    private void OffAnimator()
    {
        anm.SetBool("Walk", false);
    }
}

c# unity3d

2022-09-30 14:56

1 Answers

If you press both W and A, the Update function runs OnAnimator (-100) and
In the OnAnimator function, the following parts are running with the value of walk -100:

 if (Input.GetKey(KeyCode.A)||Input.GetKey(KeyCode.D))
{
    rb.AddForce (walk, 0, 0, ForceMode.Force);
}

Pressing only A on the other hand will run OnAnimator (100), so
The above actions are performed with a walk value of 100.

The reason is that pressing A changes the orientation of AddForce, depending on whether or not you are pressing W at the same time.

Because the situation where the variable walk becomes both X-axis and Y-axis is complicated, why don't you change the OnAnimator function as follows?
(Also make appropriate changes to calls within the Update function)

private void OnAnimator (intx, intz)
{
    anm.SetBool("Walk", true);
    Vector3 diff = transform.position-latestPos;
    latestPos = transform.position;

    if (diff.magnitude>0.01f)
    {
        transform.rotation=Quaternion.LookRotation(diff);
    }

    rb.AddForce(x, 0, z, ForceMode.Force);
}


2022-09-30 14:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.