简体   繁体   中英

Triggering unity animations based on GameObject proximity

I want to create a simple script that would trigger my animation when the player would step on a specific tile. However, it is not triggering!

To achieve this, I created an invisible (mesh renderer disabled) GameObject. The animator, attatched to the group I'm animating defaults to an idle state.

To said group, I apply this script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AnimTurretFromWall : MonoBehaviour {

    public Animator anim;
    public GameObject triggerPanel;
    public Transform player;
    public int minDistanceFromTriggerPanel;


    // Use this for initialization
    void Start () {
        anim = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update () {
        Vector3 distance = player.position - triggerPanel.transform.position;
        if (distance.magnitude < minDistanceFromTriggerPanel)
        {
            anim.Play("TurretFromWall");
        }

    }
}

for the Transform player , I'm using the FPS Controller from Standard Assets. The triggerPanel is the invisible GameObject.

You could also just use a OnTriggerEnter() function to start your animation.

 void OnTriggerEnter (Collider other)
{ 
    if(other.gameobject.tag == "Player")
    {
      // animation code
      Debug.Log("animation started..."); 
    }
}

From here, be sure to add a BoxCollider to your tile, and tick the Trigger option, then ensure that your Player has a Rigidbody attached to it, this is how the OnTriggerEnter() works.

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