【问题标题】:Unity3D movement right/left failUnity3D向右/向左移动失败
【发布时间】:2018-11-01 03:24:12
【问题描述】:

我正在制作一个无尽的跑步游戏,但我遇到了一个问题。我需要我的角色从左到右移动,但它不会这样做。 我需要它从左到右平稳移动,而不是在车道上。因为我的游戏会在整个路径中弹出随机对象。

我已经在 Unity 中将左右键分配给了 A 和 D。

这是我的代码吗?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Ballmove : MonoBehaviour {

public KeyCode moveL;
public KeyCode moveR;

public float horizVel = -4;
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    GetComponent<Rigidbody>().velocity = new Vector3(-4, 0, 0);

    if (Input.GetKeyDown(moveL))
    {
        horizVel = -5;
        StartCoroutine(stopSlid());
    }
    if (Input.GetKeyDown(moveR))
    {
        horizVel = 5;
        StartCoroutine(stopSlid());
    }
}
IEnumerator stopSlid()
{
    yield return new WaitForSeconds(1);
    horizVel = -4;
}
}

【问题讨论】:

  • 你调试过你的代码吗? horizVel 未分配给此代码中的任何组件,因此这意味着您没有移动任何东西。
  • 调试什么也没告诉我。但我确实找到了我的问题,谢谢你!
  • 看来你从来没有真正使用过你的 horizVel 变量,你将速度分配到最左边,不管一切
  • 也许这只是我个人的喜好,但我会使用 MovePosition 而不是设置速度。
  • @Kunak 你会提交你的解决方案作为答案吗?您可以接受自己的答案。我不想留下“我解决了,它。谢谢!”的问题。并没有列出任何实际答案。

标签: c# visual-studio unity3d


【解决方案1】:

所以基本上我忘了分配 horizVel 并且我还分配了向左移动的速度。我通过这样做解决了这个问题:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Ballmove : MonoBehaviour {

public KeyCode moveL;
public KeyCode moveR;

public float horizVel = 0;
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    GetComponent<Rigidbody>().velocity = new Vector3(-4, GM.vertVol, horizVel);

    if (Input.GetKeyDown(moveL))
    {
        horizVel = -3;
        StartCoroutine(stopSlid());
    }
    if (Input.GetKeyDown(moveR))
    {
        horizVel = 3;
        StartCoroutine(stopSlid());
    }
}
IEnumerator stopSlid()
{
    yield return new WaitForSeconds(0.5f);
    horizVel = 0;
}

}

所以这条线GetComponent&lt;Rigidbody&gt;().velocity = new Vector3(-4, GM.vertVol, horizVel); 应该是GetComponent&lt;Rigidbody&gt;().velocity = new Vector3(-4, 0, horizVel); 修复后我又添加了一些。

【讨论】:

    【解决方案2】:

    如果您想更精确地控制对象的位置,可以使用 moveposition 而不是速度。

    // Update is called once per frame
    void Update () {
        var horizVel = 0;
        if (Input.GetKey(moveL))
        {
            horizVel += 3;
        }
        if (Input.GetKey(moveR))
        {
            horizVel -= 3;
        }
    
        GetComponent<Rigidbody>().MovePosition(this.transform.position + new Vector3(-4, GM.vertVol, horizVel) * Time.deltaTime);
    }
    

    }

    【讨论】:

    • 谢谢,我试试看!
    猜你喜欢
    • 2013-08-13
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 2018-06-11
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多