- Home /
Interact with an object from a specific distance
So I have a door that I want to animate.
I have written these codes:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DoorAnimation : MonoBehaviour { public Animator DoorOpenandCloseAnimation; // Use this for initialization void Start () { DoorOpenandCloseAnimation = GetComponent<Animator>(); } // Update is called once per frame void Update () { if (Input.GetKeyDown("f")) { DoorOpenandCloseAnimation.Play("Door Open Animation"); } } }
But is there any way to trigger this animation at a specific distance. So im only able to trigger the animation from lets say 5 meters?
Answer by Casiell · Oct 09, 2018 at 09:43 PM
Format your code
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DoorAnimation : MonoBehaviour { public Animator DoorOpenandCloseAnimation; void Start() { DoorOpenandCloseAnimation = GetComponent<Animator>(); } void Update() { if (Input.GetKeyDown("f")) { DoorOpenandCloseAnimation.Play("Door Open Animation"); } } }
What you want is a Vector3.Distance method. Feed it your character position and door position and check if it's greater than whatever amount of units you want.
Answer by zakdank · Oct 09, 2018 at 10:46 PM
You could add a trigger around the door and then check for input using OnTriggerStay. That way, you can manually set the distance from the door. You could also use OnTriggerEnter and OnTriggerExit to enable and disabled seom GUI text saying "Press F to open the door".
This is a better solution in general. It's a bit more complex, but not that difficult to get right and it will scale a lot better when your project gets bigger.
Also if an answer is correct, please mark it as such, thanks. I suggest @zakdank answer after you try it