I’m sure this has been asked a million times but how can I prevent two physics objects from clipping into each other?
I’m testing out some very basic movement and I notice that the object I’m controlling is clipping into other objects. The floor, other rigidbodies, anything really. It will clip into the object only a small amount, but it causes a lot of problems. Here is an example.
All objects shown have rigidbodies, box colliders, are not using gravity, and are not Kinematic.
Here is the same set up with the red block using gravity, and the blue blocks kinematic.
Forgive me if these are just terrible examples, but the object is clipping into the others and I’m wondering how to make that stop happening.
Here is my movement code. Its extremely basic.
using UnityEngine;
using System.Collections;
public class playerController: MonoBehaviour {
public float xSpeed = 5f;
public float ySpeed = 5f;
void Update() {
if (Input.GetKey ("d")){
transform.Translate(xSpeed*Time.deltaTime,0f,0f);
}else if (Input.GetKey("a")){
transform.Translate (-xSpeed*Time.deltaTime,0f,0f);
}
if (Input.GetKey("w")){
transform.Translate (0,ySpeed*Time.deltaTime,0);
}else if (Input.GetKey("s")){
transform.Translate (0,-ySpeed*Time.deltaTime,0);
}
}
}
-create a new layer, name it redbox or something like that
-set your red box to that layer.
-duplicate your main camera and cal it camera2 or something like that
-on main cameras culling mask make sure redbox is unchecked
-on maincamera set depth to -1
-on camera2’s culling mask make sure everything except redbox is unchecked.
-set camera2 to depth only.
I know this is really old, but for those who still care, you need to use the Rigidbody’s velocity instead of translation, so that the physics engine can properly collide the objects
You need to use ApplyForce() on the rigidbody. When you use Transform it just teleports the object over a little each frame, resulting in clipping. If you use ApplyForce(), it uses the physics engine like WillTheGameDecoderSaid
// First get a reference to the rigidbody on your character
Rigidbody rb = gameObject.GetComponent<Rigidbody>();
// ApplyForce needs a Vector3 to know which direciton to apply force
Vector3 forceDirection = (x, y, z)
// Then apply a force to it.
rb.ApplyForce(forceDirection, ForceMode.Impulse);
There is of course some more coding you have to do (ie you need to apply force in the direction of the player input) but some googling will get you the rest of the way if you can’t figure it out yourself.