- Home /
Rigidbody Collision Help
im using the 2D platformerController in unity and it comes with a PushBodiesScript which allows the Player to push rigidboies around, but only side to side. what would i need to add so the player can push objects up and down? how would i do this?
// Script added to a player for it to be able to push rigidbodies around.
// How hard the player can push var pushPower = 0.5;
// Which layers the player can push // This is useful to make unpushable rigidbodies var pushLayers : LayerMask = -1;
// pointer to the player so we can get values from it quickly private var controller : PlatformerController;
function Start () { controller = GetComponent (PlatformerController); }
function OnControllerColliderHit (hit : ControllerColliderHit) { var body : Rigidbody = hit.collider.attachedRigidbody; // no rigidbody if (body == null || body.isKinematic) return;
// Only push rigidbodies in the right layers var bodyLayerMask = 1 << body.gameObject.layer; if ((bodyLayerMask & pushLayers.value) == 0) return;
// We dont want to push objects below us
if (hit.moveDirection.y < -0.3) return;
// Calculate push direction from move direction, we only push objects to the sides // never up and down //var pushDir = Vector3 (hit.moveDirection.x, 0, hit.moveDirection.z); Original side to side // var pushDirY = Vector3 (hit.moveDirection.y, 0, hit.moveDirection.z); up and down but side to side dosent work var pushDir = Vector3 (hit.moveDirection.x, 0, hit.moveDirection.z);
// push with move speed but never more than walkspeed body.velocity = pushDir pushPower Mathf.Min (controller.GetSpeed (), controller.movement.walkSpeed); //body.velocity = pushDirY pushPower Mathf.Min (controller.GetSpeed (), controller.movement.walkSpeed);
}
i want to know what do i need to add so the player can push objects up and down?
how would i do this?
Answer by Meltdown · Mar 20, 2011 at 09:40 AM
You're better off trying to first understand 'what' the code you have written does, then it will be much easier to know how to push products in different directions.
var pushDir = Vector3 (hit.moveDirection.x, 0, hit.moveDirection.z);
pushDir takes a 3 dimensional vector. With the x component being I assume the direction of x of your player, the y component being 0 (meaning it stays at the same height), and z being the z movement of your character.
You simply need to understand what a vector is in 3d space. To push an object up or down, you need to manipulate the y component of the vector. You currently have it as 0, meaning the object will never go up or down. So play around editing this value and the pushDir will begin pushing objects up and down.
i tried this var pushDir = Vector3 (hit.moveDirection.x, hit.moveDirection.y, hit.moveDirection.z);
but it still doesnt work ?
Try using RigidBody.AddForce on the object you are pushing ins$$anonymous$$d of setting the velocity.