A ball-like UI game object is supposed to bounce around the menu screen. It can collide with the screen edges or several other UI game objects (example: buttons).
The following code is how I complete this collision on the screen edges:
void Awake()
{
v = Quaternion.AngleAxis(Random.Range(0.0f, 360.0f), Vector3.forward) * Vector3.up; //calculate a random angle to start moving the ball-like UI object when the menu loads
}
void Update()
{
transform.position += v * _speed * Time.deltaTime; //moving the UI game object
if (transform.position.x >= _right + _canvasX)
{
v.x *= -1.0f; // if the game objects x position is greater than the boundary of the right side of the screen invert the x movement (I don't do this to the left side because there is a UI game object blocking the left side in which the moving ball-like UI game object isn't supposed to be able to pass through)
}
if(transform.position.y >= _top + _canvasY || transform.position.y <= _bottom + _canvasY)
{
v.y *= -1.0f; //do the same for the top and bottom of the screen as I did above, but invert the movement on y axis.
}
}
This works perfectly however it doesn’t for collision with other objects.
I have tried using box colliders around the other UI objects the moving object is supposed to collide with and use OnCollisionEnter2D. However, sometimes the moving object still passes right through the collision zone. I’m thinking it does this because it is only detecting the collision as the game object enters the collider. I’m thinking the issue might be that it’s only doing this once as the object collides. If the object happens to still be in the collision zone after movement is inverted no more inversion is applied and it continues on it’s trajectory through the game object. I tried solving this issue by removing the box colliders and writing out the collision restrictions similar to how I have done for the screen edges however this seems to yield the exact same result.
The collisions work 90% of the time but I don’t want there to be any chance of the object leaving the screen entirely. Any suggestions?