Unity3D运动左右失败

时间:2018-10-30 09:16:52

标签: c# visual-studio unity3d

我正在制作无尽的亚军游戏,但我遇到了问题。我需要我的角色从左到右移动,但不会这样做。 我需要它从左向右平滑移动,而不是在车道上移动。由于我的游戏将在整个路径中弹出随机对象。

我已经在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;
}
}

2 个答案:

答案 0 :(得分:0)

所以基本上我忘了分配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<Rigidbody>().velocity = new Vector3(-4, GM.vertVol, horizVel);应该是GetComponent<Rigidbody>().velocity = new Vector3(-4, 0, horizVel);,自修复以来,我还添加了一些内容。

答案 1 :(得分:0)

如果要更精确地控制对象的位置,可以使用移动位置代替速度。

// 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);
}

}

相关问题