- Home /
play animation on keypress if in range
I dont seem to get this right at all.. Im trying to get/make a script that does, so when you are in range of an object with an animation (like a door), you press like "D", and the door should open (Play the animation). I've had some help before, but it didnt seem to work. Here is the script i got as help, which didnt work:
public class AnimationTest : MonoBehaviour
{
private Animation _anim;
private bool closeEnough = false;
void Start()
{
_anim = this.GetComponent<Animation>();
}
void Update()
{
if (Input.GetKeyDown("k") && closeEnough == true)
{
_anim.Play("Gate");
}
}
void OnGUI()
{
if (Vector3.Distance(targetObject.transform.position, player.transform.position) < desiredDistance)
{
GUI.Label(new Rect(10, 10, 200, 20), "[k]");
closeEnough = true;
}
}
}
And it would be nice having like a range of 5 or something.
Answer by d112570 · Oct 12, 2013 at 07:26 PM
Try using the Collider, for example if you have a sphere, set the sphere collider Range to 5 and set "Is Trigger" to True, so when your inside the collider and press k, the script will activate, I use this same method for sounds and doors. Script should be attached to the collider.
Something like this
void OnTriggerStay(Collider theCollider) {
if(Input.GetKeyDown(KeyCode.E)) {
doSomething
}}
That might help :) But the script i got dosnt work.. It has a problem with the $$anonymous$$onoBehavier...
I'll post my whole door script, you can use it how ever you like. For your script you can replace the destination part if not needed, ins$$anonymous$$d of destination, let it play an animation. $$anonymous$$ake your you rename the EnterDoor to your fittings in the $$anonymous$$onoBehavior area to the same name as the script.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class EnterDoor : $$anonymous$$onoBehaviour {
public Transform destination;
public AudioClip doorSound;
public float outdoorSound;
void OnTriggerStay(Collider theCollider) {
if(Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.E)) { // Activate when key is pressed
theCollider.transform.position = destination.position; // move to new destination
audio.PlayOneShot(doorSound); // Play door sounds
}
}
}
Im not the best to C#.. im use to JS.. So its a little hard to understand :)
very well, try this Java version.
var levelName : String;
function OnTriggerStay(theCollider : Collider)
{
if(Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.$$anonymous$$)) {
audio.Play();
}
}
make sure your standing inside the collider for it to work.
Answer by Brock Beaudry · Oct 12, 2013 at 08:30 PM
Brackeys has a video tutorial which will walk you through setting up this scenario: Door Tutorial
Cheers
Answer by InfernoZYB · Oct 12, 2013 at 10:44 PM
Make a cube and resize it the the size you want the range to be then put trigger on it then in the code put if collider blah blah blah