Reputation: 4577
I have this code, to move my truck in my Scene in 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;
}
}
}
What I want is it goes from one point to another point and then return.
My scene is quite weird, so I draw a horrible picture like this.
Also, picture from the scene :
The problem is the truck is not moving and it's vibrating.
How can I solve this ?
Upvotes: 2
Views: 78
Reputation: 90901
Why are you even using a Coroutine for that?
You could actually simply do it straight forward in a simple method without having to deal with any flags or waiting like this:
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();
}
}
}
Upvotes: 4
Reputation: 5108
I think your issue will be solved if you initialize collisionTruck
as true:
bool collisionTruck = true;
Right now you have it initialized as false
and every time it is false
it will change direction:
yield return new WaitUntil(() => collisionTruck != true);
forward = !forward;
Personally I'd change the variable name to shouldChangeDirection
, leaving your code looking something like this:
/* 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;
}
}
Upvotes: 3