繁体   English   中英

使我的GameObject正确前进和跳跃的问题

[英]Issues Getting my GameObject to both Move Forward and Jump properly

我遇到了一个问题,即我的gameObject几乎没有跳跃。 我认为这与moveDirection因为当我注释掉p.velocity = moveDirection时,跳转有效。

对于如何解决这个问题,有任何的建议吗?

using UnityEngine;
using System.Collections;

public class Controller : MonoBehaviour 
{    
    public float jumpHeight = 8f;
    public Rigidbody p;    
    public float speed = 1;
    public float runSpeed = 3;
    public Vector3 moveDirection = Vector3.zero;

    // Use this for initialization
    void Start () 
    {
        p = GetComponent<Rigidbody>();
        p.velocity = Vector3.zero;
    }

    // Update is called once per frame
    void Update () 
    {
        if (Input.GetKeyDown (KeyCode.Space)) 
        {
            p.AddForce(new Vector3(0, jumpHeight, 0), ForceMode.Impulse);
        }

        Move ();   
    }

    void Move ()
    {
        if(Input.GetKey(KeyCode.D))
        {
            transform.Rotate(Vector3.up, Mathf.Clamp(180f * Time.deltaTime, 0f, 360f));
        }

        if(Input.GetKey(KeyCode.A))
        {
            transform.Rotate(Vector3.up, -Mathf.Clamp(180f * Time.deltaTime, 0f, 360f));
        }

        moveDirection = new Vector3(Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical"));
        moveDirection = transform.TransformDirection(moveDirection);

        if(Input.GetKey(KeyCode.LeftShift))
        {
            moveDirection *= runSpeed;
        }
        else
        {
            moveDirection *= speed;
        }

        p.velocity = moveDirection;
    }
}

尝试为您的jumpheight变量使用更高的值。 我通常会带几百个东西。

因为在字面上在同一帧内执行AddForce(...)之后,您立即使用moveDirection覆盖了速度。 您应该添加当前速度,而不是像这样完全覆盖它:

Vector3 velocity = p.velocity;
p.velocity = velocity + moveDirection;

这就是Unity警告不要直接搞乱速度的原因 ,最好为运动做另一个AddForce(...)

p.AddForce(moveDirection * Time.deltaTime);

编辑:

我不喜欢偏离OP的问题太多,但是您的新问题可能是因为您对moveDirection所做的事情太多了,我什至不明白为什么一半,但大部分情况下看起来应该是这样的:

moveDirection = new Vector3(Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical")).normalized;
float _speed = Input.GetKey(KeyCode.LeftShift) ? runspeed : speed;

p.AddForce(moveDirection * _speed * Time.deltaTime);

好吧,我想出了解决方法。 而不是将这些MoveDirection变量更改为

if(Input.GetKey(KeyCode.W)) {
        transform.position += transform.forward * Time.deltaTime * speed;
    }
    if(Input.GetKey(KeyCode.S)) {
        transform.position -= transform.forward * Time.deltaTime * speed;
    }

现在可以正常工作了。

暂无
暂无

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

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