Hello, I’m new to Unity and C# and currently making a stealth sim.
This is a part of a script that makes it’s sprite match it’s npc’s walk direction. It is being called in Update() and what it does it taking npc’s position a frame before and at the moment and compares them, deciding which coordinate has changed more and how.
I can’t seem to figure out how to make this another way, if you know how to, please, help me.
Thanks in advance!
`
void SpriteUpdate()
{
nowPos = transform.position;
/* Code below is made in case
if coordinates are negative, since
otherwise it would return reversed
direction
*/
if(prevPos.x <= 0)
{
xDiff = Mathf.Abs(prevPos.x) - Mathf.Abs(nowPos.x);
}
else
{
xDiff = Mathf.Abs(nowPos.x) - Mathf.Abs(prevPos.x);
}
if(prevPos.y <= 0)
{
yDiff = Mathf.Abs(prevPos.y) - Mathf.Abs(nowPos.y);
}
else
{
yDiff = Mathf.Abs(nowPos.y) - Mathf.Abs(prevPos.y);
}
// Sprite changing part
if(Mathf.Abs(xDiff) > Mathf.Abs(yDiff))
{
if(xDiff > 0)
{
GetComponent<SpriteRenderer>().sprite = sprites[0]; //Right look sprite
VisionField.transform.localPosition = new Vector2(3, 0);
}
else if(xDiff < 0)
{
GetComponent<SpriteRenderer>().sprite = sprites[1]; //Left look sprite
VisionField.transform.localPosition = new Vector2(-3, 0);
}
}
else if(Mathf.Abs(yDiff) > Mathf.Abs(xDiff))
{
if(yDiff > 0)
{
GetComponent<SpriteRenderer>().sprite = sprites[2]; //Up look sprite
VisionField.transform.localPosition = new Vector2(0, 3);
}
else if(yDiff < 0)
{
GetComponent<SpriteRenderer>().sprite = sprites[3]; //Down look sprite
VisionField.transform.localPosition = new Vector2(0, -3);
}
}
else
{
GetComponent<SpriteRenderer>().sprite = sprites[4]; // Idle sprite
VisionField.transform.localPosition = new Vector2(0, 0);
}
}
Hi,
I’m not sure why your sprite is not just a child object of your NPC?
Just drag and drop it the sprite on the NPC in the project window.
Remove this script and see if that works.