- Home /
Having problems setting references to GetComponent Script function return values
I am trying to get a vector2 from a pacMan script function so I can find the distance between pacman and an enemy.
I want to subtract pacman's position from an enemy position.
Here is my code from the enemy class:
private Vector2 pacPos;
private Vector2 position;
private GameObject pacman;
private PlayerScript pacManScript;
privateVector2 v;
void Awake ()
{
pacman=GameObject.Find("PacMan");
pacManScript=pacman.GetComponent<PlayerScript>();
}
void Start ()
{
position=new Vector2(1,1);
pacPos= pacManScript.getPosition();
v=pacPos-position;
print("distance between pacman which is "+ pacPos+ " and inky's "+ position+ "is " + v);
}
Here it is not working, it does the math wrong when it prints.
When I do this though it works:
print("distance between pacman which is "+ pacManScript.getPosition()+ " and inky "+ position+ "is "+ (pacManScript.getPosition()-position));
I was wondering how come this is the case? It seems that my pacPos reference to pacManScript.getPosition() doesent work the way I want it to.
Thank you...I really want to understand GetComponent.
Take Care.
Answer by vptb · May 28, 2014 at 11:26 AM
To get the distance between 2 vectors you should use Vector2.Distance(pacPos, position);
When you do v = pacPos - position, you're calculating the direction vector starting from position and ending at pacPos.
Thanks for answering I totally agree with you. However, I am still having problems with the pacPos, it gets assigned a (0,0) vector2 when I do this code. (it should be a differnt vector):
pacPos= pac$$anonymous$$anScript.getPosition();
I do not know why it gets this incorrect vector.