我有这段代码,可以在Unity的场景中移动卡车:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TruckMovement : MonoBehaviour
{
Coroutine TruckC;
bool forward = false;
Rigidbody2D truck;
bool collisionTruck = false;
void Start()
{
truck = GetComponent<Rigidbody2D>();
TruckC = StartCoroutine(Truck());
}
void OnDestroy()
{
StopCoroutine(TruckC);
}
IEnumerator Truck()
{
while(true)
{
if(forward)
{
truck.velocity = Vector3.right;
}
else
{
truck.velocity = Vector3.left;
}
yield return new WaitUntil(() => collisionTruck != true);
forward = !forward;
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.tag.Equals("Bound"))
{
collisionTruck = true;
}
}
void OnCollisionExit2D(Collision2D collision)
{
if (collision.collider.tag.Equals("Bound"))
{
collisionTruck = false;
}
}
}
我想要的是从一个点到另一个点然后返回。
我的场景很奇怪,所以我画了一张可怕的照片。
此外,还有现场图片:
问题在于卡车没有移动并且在振动。
我该如何解决?
答案 0 :(得分:4)
您为什么还要为此使用协程?
实际上,您可以简单地以一种简单的方法直接执行此操作,而不必处理任何标志或像这样等待:
public class TruckMovement : MonoBehaviour
{
private bool forward = false;
private Rigidbody2D truck;
private void Awake()
{
truck = GetComponent<Rigidbody2D>();
}
private void Start()
{
// Start moving at the beginning
ChangeDirection();
}
private void ChangeDirection()
{
forward = !forward;
truck.velocity = forward ? Vector2.right : Vector2.left;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.tag.Equals("Bound"))
{
ChangeDirection();
}
}
}
答案 1 :(得分:3)
如果您将collisionTruck
初始化为true,我认为您的问题将得到解决:
bool collisionTruck = true;
现在您已将其初始化为false
,并且每次将其初始化为false
都会改变方向:
yield return new WaitUntil(() => collisionTruck != true);
forward = !forward;
我个人将变量名更改为shouldChangeDirection
,使您的代码看起来像这样:
/* More stuff */
bool shouldChangeDirection = false;
/* More stuff*/
IEnumerator Truck()
{
while(true)
{
if (forward)
{
truck.velocity = Vector3.right;
}
else
{
truck.velocity = Vector3.left;
}
yield return new WaitUntil(() => shouldChangeDirection);
forward = !forward;
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.tag.Equals("Bound"))
{
shouldChangeDirection = true;
}
}
void OnCollisionExit2D(Collision2D collision)
{
if (collision.collider.tag.Equals("Bound"))
{
shouldChangeDirection = false;
}
}