One of the features I have in my game is a type of lift system. I have a cube that will raise and lower, and if a player gets on this cube, it will lift the player. If the player is under it, it will crush him or her.
I’m using physics.RaycastAll to do the collision detection. I’m using RaycastAll because I have many other objects that have the possibility of colliding with the player for different effects.
My issue is that if the lift moves too fast, it will go through the player instead of picking the player up, or crushing the player. I’m using a Lerp on the lift, and the speed isn’t ridiculous. I do actually see the lift move the player, but then the player plops through it and stays on the ground.
Here is a bit of code that shows what I’m doing:
void LateUpdate(){
// down (above object)
// Check on each side of the player to cover the whole player.
for (int i = 0; i < 2; i ++){
switch (i){
case 0:
hits = Physics.RaycastAll(middleRight, -Vector3.up, (collider.bounds.size.y * 0.5f));
break;
case 1:
hits = Physics.RaycastAll(middleLeft, -Vector3.up, (collider.bounds.size.y * 0.5f));
break;
default:
hits = null;
Debug.Log("Too many collision attemps!");
break;
}
int j = 0;
while (j < hits.Length){
hit = hits[j];
switch(hit.transform.gameObject.layer){
case 1: // lift. We store the player in an array on the lift itself so the player is moved by the lift.
pScript = hit.transform.gameObject.GetComponent<MovingPlatform>();
moveVector.y = 0;
airborne = false;
carried = true;
// Only add it if we don't have it on our carry list
get = true;
foreach (GameObject gO in pScript.carriants){
if (gO == gameObject){
get = false;
}
}
if (get){
pScript.carriants.Add(gameObject);
pScript.carrying = true;
}
transform.Translate(0,(collider.bounds.size.y * 0.51f)-hit.distance,0); // Move the player out of the object
break;
case etc...
break;
}
}
}
If I move the lift slowly, it seems to work fine. But, I have to move it rather slow…
I’m also up for any code critiques if available. For example, is there a better way to use raycast collision with multiple rays to cover a larger area?
Thanks.