我有一种"bug";在我的代码中,我只是找不到为什么会发生这种情况以及如何修复它(我是unity的初学者,在unity的手机游戏中更是如此(
我使用触摸让玩家左右移动,但问题是我希望玩家在手指左右滑动时能平稳移动,但我的代码也会将玩家移动到你点击的地方,而不仅仅是当你滑动时。
任何帮助都将不胜感激,谢谢大家:(
我的代码:
public float playerspeed = 500f;
public float directionalspeed;
void Start()
{
}
void Update()
{
float movehorizontal = Input.GetAxis("Horizontal");
transform.position = Vector3.Lerp(gameObject.transform.position, new Vector3(Mathf.Clamp(gameObject.transform.position.x + movehorizontal, -1f, 1f), gameObject.transform.position.y, gameObject.transform.position.z), directionalspeed * Time.deltaTime);
// -------------------------MOBILE CONTROLS SECTION STARTS HERE ------------------------------------------------
GetComponent<Rigidbody>().velocity = Vector3.forward * playerspeed * Time.deltaTime;
//collects the postion of the finger on the screen
Vector2 touch = Camera.main.ScreenToWorldPoint(Input.mousePosition + new Vector3(0, 0, 10f));
//if there are more then 0 fingers on the screen , move the ball smoothly on the X axis to where the finger is pointing
if (Input.touchCount > 0)
{
transform.position = new Vector3(touch.x, transform.position.y, transform.position.z);
}
}
试试这个:
void Update()
{
//other code
if (Input.touchCount > 0)
{
//you might want to lower playerSpeed
if (transform.position.x > touch.x)
{
transform.Translate(Vector3.left * playerSpeed * Time.deltaTime);
}
else if (transform.position.x < touch.x)
{
transform.Translate(Vector3.right * playerSpeed * Time.deltaTime);
}
}
}