Reputation: 35
Classic Stacker game that the ice cream should go across the screen. It works and moves the object but sometimes it gets stuck on the sides of the screen like this
Here is the code
private float min_X = -2.48f, max_X = 2.48f;
private float move_Speed = 60f;
void Start()
{
GamePlayController.instance.currentBox = this;
canMove =true;
if (Random.Range(0, 2) > 0){
move_Speed *= -1f;
}
}
void MoveBox(){
if (canMove)
{
Vector3 temp = transform.position;
if (temp.x > max_X)
{
move_Speed *= -1f;
}
else if (temp.x < min_X)
{
move_Speed *= -1f;
}
temp.x += move_Speed * Time.deltaTime;
transform.position = temp;
}
}
Upvotes: 0
Views: 114
Reputation: 418
You need to only flip the direction once when it reaches the edge. Currently you could be flipping it back and forth every frame once it is above or below the max and it would never get back inside the range
Something like this should work
private float min_X = -2.48f, max_X = 2.48f;
private float move_Speed = 60f;
private int direction = 1;
void Start()
{
GamePlayController.instance.currentBox = this;
canMove =true;
if (Random.Range(0, 2) > 0){
direction *= -1f;
}
}
void MoveBox(){
if (canMove)
{
Vector3 temp = transform.position;
if (temp.x > max_X)
{
direction = -1f;
}
else if (temp.x < min_X)
{
direction = 1f;
}
temp.x += move_Speed * Time.deltaTime * direction;
transform.position = temp;
}
}
Upvotes: 1