简体   繁体   中英

I'm trying to figure out what is the best way to prevent from the player to move through walls and other objects?

I can think of what objects I will use in the game and add them a box collider or mesh collider and start setting them up. Or I could use maybe raycast and detect the distance from the objects I want to avoid walking through? Is that logic to use distance calculation with raycast?

void FixedUpdate()
{
    Vector3 direction = new Vector3(transform.position - lastPosition);
    Ray ray = new Ray(lastPosition, direction);
    RaycastHit hit;
    if (Physics.Raycast(ray, hit, direction.magnitude))
    {
        // Do something if hit
    }

    this.lastPosition = transform.position;
}

Not sure if this is the right script to put on the player. Maybe need to use layer? But the logic is that if the player is for example 0.3f distance form the object that the player will stop moving forward.

Using unity you don't really want to be doing any of this stuff from the code behind, instead you'd have a RigidBody or RigidBody2D component on your "player", and then a box Collider or mesh collider (or the 2d versions of those) on your collision objects.

This will handle all collisions and stop the player when they hit that object.

Another word of advice is, when handling collisions in the backend you don't want to use FixedUpdate as if an object is travelling fast enough it will pass through the collider between updates

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM