- Home /
Why is this not giving me an offset
Hello!
I'm currently trying to make a simple AI for a spaceflight game, and I want to "cap" how close the AI can be to the player, I made a script using the transform.position.magnitudes to make sure they didn't get closer then the desired offset. However it aint working and I have absolutely no idea of why.
if(-offsetfromplayer <= (enemytransform.magnitude - this.gameObject.transform.position.magnitude) && (enemytransform.magnitude - this.gameObject.transform.position.magnitude) < 0f){
movementspeed = 0f;
localvelocity = new Vector3(0f,0f, movementspeed);
}
offsetfromplayer is 50 by the way. Which means that -offsetfromplayer is -50.
As you can see this is when the magnitude difference is negative, and it is negative when I do the tests. I know that because I've got the magnitude differences show up in the inspector. So that is updating correctly, -offsetfromplayer also show up correctly in the console. And that should work as long as the magnitude differences is between -50 and 0. Right?
Answer by robertbu · Jul 15, 2014 at 04:49 AM
The code you have is a bit confusing. magnitude is a property of a Vector3, not a transform, but you call your variable 'enemytransform'. If it really is a Transform, you should be getting a compiler error.
But from a logic standpoint, this code is also wrong. Let's assume that 'enemtransform' is a Vector3. If so, you find the distance between the two objects by:
float dist = (transform.position - enemytranform).magnitude;
So your code would be:
if ((transform.position - enemytransform).magnitude < offsetfromplayer) {
movementspeed = 0.0f;
lovalvelocity = Vector3.zero;
}
enemytransform is initialized(Updated?) in the beggining of FixedUpdate.
After some more looking around I found Vector3.Distance which is what I use now ins$$anonymous$$d. But thanks anyway!
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Android back button always quits app. 1 Answer
EnemyAI C# Error 1 Answer
Rigidbody (Player) goes through wall 1 Answer