简体   繁体   English

在 Unity3D 中使用操纵杆平稳移动

[英]Smooth movement using joystick in Unity3D

I try to accomplish smooth movement with the Xbox Controller, however it is very snappy, even though snap is turned of and deadzone set to 0. Movement with keyboard however is very smooth, so I assume GetAxis does not work with a controller, it's always GetAxisRaw.我尝试使用 Xbox Controller 完成平滑移动,但是它非常活泼,即使关闭了 snap 并且死区设置为 0。但是使用键盘移动非常平滑,所以我认为 GetAxis 不适用于 controller,它总是获取轴原始。 So I switched to GetAxisRaw and tried to smooth everything out.所以我切换到 GetAxisRaw 并试图平滑一切。 Even with acceleration, the movement is still very jagged and snappy.即使有加速,运动仍然非常锯齿和敏捷。 Does anyone have an idea how to get a nice smooth movement with a controller, like keyboard + GetAxis?有谁知道如何使用 controller(如键盘 + GetAxis)获得良好的平稳运动?

public class PlayerController : MonoBehaviour
{
CharacterController cc;

float acceleration = 0;

[SerializeField] float speed;
[SerializeField] float acclerationRate = 1;
private void Awake()
{
    cc = GetComponent<CharacterController>();
}

private void Update()
{
    float deadzone = 0f;
    Vector2 stickInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
    if (stickInput.magnitude < deadzone)
        stickInput = Vector2.zero;
    else
        stickInput = stickInput.normalized * ((stickInput.magnitude - deadzone) / (1 - deadzone));

    if (stickInput.x != 0 || stickInput.y != 0)
    {
        acceleration += Time.deltaTime * acclerationRate;
        acceleration = Mathf.Clamp01(acceleration);
    }
    else
    {
        acceleration = 0;
    }

    cc.Move(new Vector3(stickInput.x, 0, stickInput.y) * speed * acceleration * Time.deltaTime);


}
}

I would keep track of your player's velocity and use MoveTowards to adjust it based on the input.我会跟踪玩家的速度并使用MoveTowards根据输入进行调整。 Don't forget to clamp your input's magnitude so your character doesn't travel diagonally faster than orthogonally in the event the player prefers keyboard input.不要忘记限制输入的幅度,这样在玩家更喜欢键盘输入的情况下,角色的对角线移动速度不会比正交移动快。

CharacterController cc;

[SerializeField] float speed;
[SerializeField] float acclerationRate = 1;
[SerializeField] float deadzone = 0f;

Vector3 velocity;

private void Awake()
{
    cc = GetComponent<CharacterController>();
    velocity = Vector3.zero;
}

private void Update()
{

    Vector3 stickInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, 
            Input.GetAxisRaw("Vertical"));
 
    if (stickInput.magnitude < deadzone)
    }
        stickInput = Vector3.zero;
    }
    else
    {
        float clampedMag = Mathf.Min(1f, stickInput.magnitude);
        stickInput = stickInput.normalized * (clampedMag - deadzone) / (1f - deadzone);
    }

    velocity = Vector3.MoveTowards(velocity, stickInput, 
            accelerationRate * Time.deltaTime);

    cc.Move(velocity * Time.deltaTime);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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