[英]Unity3D movement right/left fail
I'm making an endless runner game, and I have stuck on a problem. 我正在制作无尽的亚军游戏,但我遇到了一个问题。 I need my charater to move left to right, but it wont do it.
我需要我的角色从左到右移动,但不会这样做。 I need it to move smooth from left to right and not in lanes.
我需要它从左向右平滑移动,而不是在车道上移动。 Since my game will be having random object popping up all over the trail.
由于我的游戏将在整个路径中弹出随机对象。
I have assigened the left and right key to A and D in Unity. 我已经在Unity中将左右键辅助到了A和D。
Is it my code? 是我的代码吗?
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;
}
}
So basically I forgot to assign horizVel and I also assigned the velocity to go left. 所以基本上我忘了分配horizVel,而且我还分配了向左移动的速度。 I fixed the problem by doing this:
我这样做来解决了这个问题:
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;
}
}
So this line GetComponent<Rigidbody>().velocity = new Vector3(-4, GM.vertVol, horizVel);
所以这行
GetComponent<Rigidbody>().velocity = new Vector3(-4, GM.vertVol, horizVel);
should be GetComponent<Rigidbody>().velocity = new Vector3(-4, 0, horizVel);
GetComponent<Rigidbody>().velocity = new Vector3(-4, 0, horizVel);
I have added some more since the fix. 自修复以来,我还添加了一些其他功能。
You could use moveposition instead of velocity if you want to have more precise control over the object's position. 如果要对对象的位置进行更精确的控制,可以使用移动位置而不是速度。
// 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);
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.