- Home /
[C#] Raycast based physics and clipping
I'm working on a platforming game with raycast physics and I'm having some trouble with clipping. This is the section of code thats applying gravity
for(int i = 0; i < verticleRays; i ++){ lerpPosition = lerpPosition + lerpAmount; Vector2 origin = Vector2.Lerp(startPoint, endPoint, lerpPosition); bool clipped = true; if(origin.x == endPoint.x)origin.x = startPoint.x;
RaycastHit2D hitInfo = Raycaster(rayLength, Vector2.up, origin, newVelocityY);
connected = hitInfo;
print ("Collider: " + hitInfo.collider + " Point: " + hitInfo.point + " hit distance: " + hitInfo.fraction + " connected: " + connected);
if(!connected){
clipped = false;
transform.Translate(-Vector2.up * (gravity * Time.deltaTime));
velocity = new Vector2(velocity.x, 0);
print ("Gravity activated");
break;
}
if(connected){
Vector2 lastPosition = new Vector2(transform.position.x, transform.position.y);
if(hitInfo.fraction > 0.2)clipped = false;
if(hitInfo.fraction > 0){
transform.Translate(-Vector2.up * (gravity * Time.smoothDeltaTime));
velocity = new Vector2(velocity.x, 0);
print ("Gravity activated");
lastPosition = hitInfo.point;
break;
}
if(hitInfo.fraction == 0 && !clipped){
clipped = true;
Vector2 newPosition = ClipPrevent(lastPosition);
transform.position = newPosition;
break;
}
}
}
as you can see I'm using a basic transform.translate
with time.deltaTime
. The issue I'm having is that when my character drops down it'll usually pass through the floor a variable amount. Sometimes it won't pass through the floor at all but most of the time it does.
I've been working on an anti clipping method but it doesn't seem to be working. Here's the code for that
Vector2 ClipPrevent(Vector2 clipPoint){
Vector2 pcClipPoint = new Vector2(transform.position.x, -boxCollider.size.y / 2);
float clipDistance = clipPoint.y - pcClipPoint.y;
print ("Clip Distance: " + clipDistance);
if(clipDistance != 0){
Vector2 newLocation = new Vector2(transform.position.x, transform.position.y - (clipDistance));
return newLocation;
}
else return new Vector2(transform.position.x, transform.position.y);
}
again as you can see its called from the previous code and returns a vector2 which is supposed to place the character at the right spot to be just touching the floor.
So yeah if anyone could help me figure out how to make objects not clip through each other I would be super happy.
Thanks in advance.
Your answer
Follow this Question
Related Questions
Stop picked up object clipping through walls? 0 Answers
Cube clips and falls through wall when held 0 Answers
Held cube clips through wall 0 Answers
false gravity on a cube planet 6 Answers