【问题标题】:Moving rigidbody移动刚体
【发布时间】:2019-08-26 13:35:30
【问题描述】:

我是 Unity 的新手,我有一个想要移动的对象。 但是这个物体根本不动。它改变了他的方向,因此对象可以向左/向右看,但它不会从他开始的点移动。

所以基本上物体可以旋转但不能向任何方向移动。

问题是:如何让物体移动

public float movementSpeed = 20;
Animator anim;
Rigidbody rb;

public Text countText;
public Text winText;

private int count;

void Start()
{
    anim = GetComponent<Animator>();
    rb = GetComponent<Rigidbody>();
    count = 0;
    SetCountText();
    winText.text = "";
}

void FixedUpdate()
{
    ControllPlayer();
}

void ControllPlayer()
{
    float moveHorizontal = Input.GetAxisRaw("Horizontal");
    float moveVertical = Input.GetAxisRaw("Vertical");

    Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

    if (movement != Vector3.zero)
    {
        transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(movement), 0.15f);
        anim.SetInteger("Walk", 1);
    }
    else
    {
        anim.SetInteger("Walk", 0);
    }


    rb.addForce(movement * movementSpeed * Time.deltaTime);

}

public void OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("Pick Up"))
    {
        other.gameObject.SetActive(false);
        count = count + 1;
        SetCountText();
    }
}

void SetCountText()
{
    countText.text = "Food: " + count.ToString();
    if (count >= 10)
    {
        SceneManager.LoadScene("Victory");
    }
}

【问题讨论】:

    标签: c# unity3d rigid-bodies


    【解决方案1】:

    对于您需要做的事情来说,这似乎有点过于复杂了。

    目前我并没有真正在 3D 世界中做任何事情,但在 YouTube 上快速搜索会找到 this 视频。

    他使用的代码是

    transform.Translate(moveSpeed*Input.GetAxis("Horizontal")*Time.deltaTime,0f,moveSpeed*Input.GetAxis("Vertical")*Time.deltaTime); 
    

    Update() 方法中,moveSpeed 是一个公共变量,因此您可以在检查器中更改它。

    然后您可以检查您是否正在移动并相应地设置动画值。

    我总是建议将玩家移动放在Update()方法中,否则它会感觉迟钝并错过按键,特别是如果你有很多事情要做 - 例如二段跳。

    希望这会有所帮助,并祝 Unity 好运 :)。

    顺便说一句,由于您是新手,我已经建议您先在 Youtube 上搜索教程 - 大多数时候有人已经完成了您想做的事情。像Brackeys 这样的创作者积压了大量非常有用的东西。

    【讨论】:

    • 您好,感谢您的评论!好吧,我已经有一些可以工作的东西transform.Translate(movement * movementSpeed * Time.deltaTime, Space.World);,但我的老师说使用rb.addforce 可能更容易,但我无法让它工作。但无论如何,非常感谢您的评论!
    • 如果要使用物理系统,必须使用AddForce。你能放一张你的 RigidBody 组件的截图吗?也许您将属性IsKinematic 设置为true
    猜你喜欢
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多