- Home /
Enemy bounce from screen edges
I want my enemy to bounce off from the edges of the screen like in many video games. I have achieved this however, there is one problem. the enemy gets stuck on the corners since it bounces from the right corner to the left corner and to the right corner, etc. how can I solve an issue like this?
This is the way I do it, It's a 2D top-down game.
Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
if ((screenPosition.y > Screen.height) || (screenPosition.y < 0f) || (screenPosition.x > Screen.width) || (screenPosition.x < 0f))
{
screenPosition.x = Mathf.Clamp(screenPosition.x, 0f, Screen.width);
screenPosition.y = Mathf.Clamp(screenPosition.y, 0f, Screen.height);
Vector3 newWorldPosition = Camera.main.ScreenToWorldPoint(screenPosition);
transform.position = new Vector2(newWorldPosition.x, newWorldPosition.y);
if (transform.position.x >= 8f || transform.position.x <= -8f)
rg2d.velocity = new Vector2(rg2d.velocity.x * Random.Range(-1f, -0.8f), rg2d.velocity.y);
else
rg2d.velocity = new Vector2(rg2d.velocity.x, rg2d.velocity.y * Random.Range(-1f, -0.8f));
}
I am open to any suggestions.
Comment
Your answer
Follow this Question
Related Questions
Enemy's health wont get set from different script. 1 Answer
Boss Health Bar 1 Answer
While Moving Left or Right my character falls more slowly. 2 Answers
2D AI, Aim at player - even when jumping? 1 Answer
Photon position syncing 0 Answers