Preventing A Teleporting GameObject From Passing Through Walls
I created a capsule in Unity which has a box collider and a Rigidbody in it and its rotations are freezed. I have a large plane under the capsule so it doesn't fall down. And I have a script which changes the capsule's transform position by 1 in the desired position (x or z) by the keyboard input (W,A,S,D). The problem is, I have a wall in the center of the plane but when I move the capsule into the wall, the capsule doesn't stop. Instead it passes through the wall.
Answer by theterrificjd · Dec 14, 2017 at 12:26 AM
Use a Physics.LineCast between the current position and the target position. If it hits anything, change the current position to the hit point (or a point close to it on the side of the target position.
You may need to check all the syntax but basically:
Raycast hit;
int layermask = ~(1 << 8); // Layer of colliders he can pass through (should include himself)
if( Physics.Linecast( transform.position, targetPosition, out hit, layermask)){
targetPosition = hit.point;
targetPosition = Vector3.Lerp(transform.position,targetPosition,.9f);
}
Of course, you can always use a rigidbody, move with force, and then attach a collider. In that way your object will collide more naturally with the wall.
Your answer
Follow this Question
Related Questions
Slerp Rotating 1 Degree and Limiting All Other Rotation 1 Answer
Detect overlapping objects 2D game 0 Answers
How to fix snake behavior in Unity3d? 0 Answers
OnTriggerEnter Issue - Collider problem 0 Answers