I’m controlling the bat with the mouse, the problem is that the mouse can overtake the ball when it is travelling on the x axis and collide with it multiple times, causing the ball to behave strangely and stick to the bat.
My solution was to store what the ball collided with last, and if the last collision was with the bat, the ball can’t collide with the bat again until it has collided with something else (block, wall, another ball etc).
My script so far is in C#, and although I thought that the array function was the way to do it, it seems that is only available in javascript.
I’m sure I’ve done some debugging on a tutorial at some stage that stored the last object hit but I’ve done so many I can’t remember which one it was.
Any help, even just pointing me towards the necessary function would be appreciated.
Thanks.
Collision lastCollision;
void CheckLastCollision()
{
if(lastCollision)
{
if(lastCollision.gameObject.name == "Bat")
{
// Collided with the bat last time
}
}
}
void OnCollisionEnter(Collision coll)
{
lastCollision = coll;
}
This creates a ‘lastCollision’ variable, which gets updated at every collision. You can check the last collision with the CheckLastCollision() function. If you want to check it on collision, be sure to write it at the beginning of the OnCollisionEnter void, so it will check the last collision first, then assign the new collision to it.
By the way, you can use
Collision[] lastCollisions;
to create an array of collisions, if you want to check a collision history. Be sure to initialize the array in the Start() method with
lastCollisions = new Collision[length];
and replace ‘length’ with a number. The update of this array is the following:
for(int i = 0; i < lastCollisions.Length - 1; i++)
{
lastCollisions *== lastCollisions[i + 1];*
}
lastCollisions[lastCollisions.Length - 1] = coll;
The function will first replace every collision in the array (starting from index 0) with the next collision in the array. Then the last one is replaced with the fresh collision (‘coll’).
However, the array has a fixed size. If you want a dynamic-sized container, you could use lists.
using System.Collections.Generic;
List lastCollisions = new List();
lastCollisions.Add(coll);
lastCollisions.RemoveAt(index);
The first line will create a list with the type of Collision, so it can hold only collisions. The second line can be used to add a collision to the list (the variable is named with ‘coll’, and it will be added to the end of the list). The third line can be used to remove a collision in the list with an index number.