简体   繁体   中英

Unity forcing physics engine to check collisions

I am creating a game in unity where the player can drag one object (a card) over another (an enemy). If they drag the card over the enemy I want to run some code, and if not I want to return the card to its initial position. I placed a collider on both objects but it isnt working the way it should. I am assuming this is because the object is getting moved back to its initial location before the physics engine sees the collision, but I don't know how to fix this. I am deactivating the collider on the card while moving it to avoid having it trigger collisions until the player has placed it using the onmousedown and onmouseup events. Any tips on how to fix this behavior? can I force the physics engine to check collisions with the onmouseup event? I know the collisions are working because when I turn off the return to initial position behavior the game functions as expected.

How about useing the collider as trigger and do not use rigidbodys or anything. Then if there is a trigger enter event set bool as true. If there trigger exit reset the bool to false.

Now if you "Release" the card check if bool is true or false.

  • true: Set the cards position to the player or what you want
  • false: Reset the cards position to the start

Now beeing a little mroe fancy you can set a lighted border around the card when bool is active (just check in update)

Example:

public class Card : MonoBehaviour {
    private bool isHolding;
    private bool isHovering;

    public Vector3 startPos;

    public void Start() {
        startPos = transform.position;
    }
    
    public void Update() {
        // Code where you check if the card is Clicked and Moved by the player
        // If so set isHolding = true
        
        // dont enter the check if holding blablabla when animation stuff is happening
        if (doAnimationStuff) {
            // do animation
            // Destroy Object
            return;
        }
        
        // Code to check if isHolding == false
        if (!isHolding) {
            if (!isHovering) {
                transform.position = startPos;
            } else {
                doAnimationStuff = true;
            }
        }
    }

    private void OnTriggerEnter(Collider other) {
        // Check if other is a player
        // if so set isHovering = true
    }

    private void OnTriggerExit(Collider other) {
        // Check if other is a player
        // if so set isHovering = false
    }
}

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