不同的前进,后退和扫射速度

时间:2017-12-13 09:13:59

标签: unity3d

我使用此代码使我的fps角色移动:

CharacterController controller;

void Awake()
{
    reference = new GameObject().transform; 
}   
void Update()
{
    controller.Move (moveDirection * Time.deltaTime);
    reference.eulerAngles = new Vector3(0, mycamera.eulerAngles.y, 0);
    forward = reference.forward;
    right = new Vector3(forward.z, 0, -forward.x);
    float hor = Input.GetAxisRaw("Horizontal");
    float ver = Input.GetAxisRaw("Vertical");
    targetDirection = (hor * right) + (ver * forward);
    targetDirection = targetDirection.normalized;
    targetVelocity = targetDirection;

    if (inputDetected)
    {
        targetVelocity *= speed;
        moveDirection.z = targetVelocity.z;
        moveDirection.x = targetVelocity.x;
    }
}

这很有效,但我希望我的角色具有不同的向前,向后和扫射速度。我已经尝试了targetVelocity.x *= speed1;targetVelocity.z *= speed2;,但这不起作用。当我移动鼠标的那一刻,当按下前进键时,角色不再前进,而是倾斜。

1 个答案:

答案 0 :(得分:0)

这不起作用,因为前向与速度矢量的z值不同。速度矢量中的值是世界空间值。

实现您想要的最简单方法是将速度差直接应用于您的输入。例如(不是最好的解决方案,只是为了给你一个快速的想法)

float ver = Input.GetAxisRaw("Vertical"); //-1 to 1
float forwardSpeedMultiplier = 1f;
float backwardSpeedMultiplier = .6f;

//If input >= 0 then use forwardspeed multiplier
// else use backwardspeedmultiplier
float speedMultiplier = (ver >= 0) ? forwardSpeed: backwardSpeed;

//Multiply input value with the multiplier
ver *= speedMultiplier;

修改

这是更好的版本

public class Move : MonoBehaviour {
    public float forwardMultiplier = 1.2f;
    public float backwardMultiplier = .5f;
    public float sidewardMultiplier = .7f;
    public float speed = 5f;

    private Rigidbody rb;

    // Use this for initialization
    void Start () {
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update () {
        var input = transform.rotation * new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));        
        var dotResult = Vector3.Dot(input.normalized, transform.forward);
        var speedMultiplier = (dotResult >= 0) ? Mathf.Lerp(sidewardMultiplier, forwardMultiplier, dotResult) : Mathf.Lerp(sidewardMultiplier, backwardMultiplier, Mathf.Abs(dotResult));
        var movementVector = input * speed * speedMultiplier;
        movementVector.y = rb.velocity.y;
        rb.velocity = movementVector;
    }
}