Home > Back-end >  How move object with collision (without physics) Unity
How move object with collision (without physics) Unity

Time:08-30

I have 3d cube which have 3d box collider.

I want to write jump system for cube with collision, but without physics (without gravity, without rotation, etc) (Like 3d platformer)

CodePudding user response:

There is a great way of doing this. You will still need physics.

The Steps

  • Have a rigidbody on your player.
  • There should be a dropdown menu called spmethiing like "constraints". Find it.
  • Then Set all rotation constraints in this menu to true.

However, I don't understand why you wouldn't want gravity. Don't all platformers have gravity? (There must be some force to pull your player down when they jump). Anyways, if you don't want gravity, then you must uncheck Use Gravity variable.

**Notes: **

  • To control your player, you must use AddForce(). If you have any questions about adding force, let me know in the comments.

:) Thanks.

CodePudding user response:

You can take advantage of the Physics.OverlapBox API to check for collisions before committing to move your object.

Your code will look something like this:

Vector3 nextPosition = transform.position;
/*
  You do your normal movement code, but apply 
  it to nextPosition instead of transform.position
*/
Collider[] hitColliders = Physics.OverlapBox(nextPosition, transform.localScale/2);
if(hitColliders.Length == 0){
  transform.position = nextPosition;
}

Note that the object itself shouldn't have a collider, otherwise it will detect itself. You also shouldn't move in big steps as this method doesn't take colliders on the path into account.

  • Related