- Home /
Stop Moving at a Certain Distance from a Hit Box
I'm having a problem with my fighting game which has to do with an interaction between two objects: a guarding character and an attacking "hit box." What I want to do is have the character stop moving when a hit box prefab has its type variable set to "attack". I have no idea how to do that though. Is there a way that I can not only find another object, calculate distance, and also access its variables or is there a better way to do it? I've tried starting with:
hitBox = GameObject.FindWithTag("hitBox");
if(hitBox.GetComponent("hitBox").GetType == "attack" || hitBox.GetComponent("hitBox").GetType == "projectile"){
Debug.Log(GameObject.FindWithTag("hitBox").transform.position);
}
But this returns an NullReferenceException error and nothing is printed onto my debug log. I've also tried just GameOjbect.Find, but that didn't work either. My question might be a little confusing, so even if you're unsure exactly what I'm trying to ask, any help is appreciated.
Answer by zebra6595 · Jul 21, 2015 at 02:51 AM
you could try putting a collider on your character that's the size of the area or distance you want and use it as a trigger.
That's a good idea, but I'm already using a collider for actual collisions. Thanks for your input!
you could also use a raycast and check the tag of what it hits and the distance something like this for 3d if (Physics.Raycast (new Vector3(0,0,0),Vector3.forward, out hit, 100)&& hit.transform.tag == "player"&& hit.distance<=stopdistance) { stop player here } for 2d
if (Physics2D.Raycast (new Vector2(0,0),Vector2.right, out hit, 100)&& hit.transform.tag == "player"&& hit.distance<=stopdistance) { stop player here }
Actually, I came up with an idea and adapted your original answer. What I did was make the hit box create another box that would act as its second box collider that lets a guarding character to stop moving when it gets close. $$anonymous$$y code went like this:
//This code pertains to the guarding character.
var rangeOf : Transform;
var inRange : boolean;
function Update () {
if(rangeOf == null && (type == "guarding" || type == "neutral")){
rangeOf = null;
inRange = false;
}
}
//When within the range of a guardRange, do not move.
function OnTriggerStay(range : Collider) {
if(range.gameObject.tag == "guardRange" && type == "guarding"){
//Saves the extra box as a variable so that eventually when it disappears, or becomes null, inRange will be false (as shown in the Update function).
rangeOf = range.transform;
inRange = true;
}
}
//And just in case a guarding character is at the edge of the box and exits it (due to drag), inRange will also be false.
function OnTriggerExit(range : Collider){
if(range.gameObject.tag == "guardRange" && (type == "guarding" || type == "neutral")){
rangeOf = null;
cameFrom.GetComponent("$$anonymous$$ove").inRange = false;
}
}
Thank you very much for your help, zebra6595!
Your answer