- Home /
How to make a sprite walk on its own?
I want to make a sprite move around on it's own, like an npc, is this possible? I've tried a few scripts but they were from 2013 I realised after using them and testing them on monodevelop and to see there was 5 errors, if anybody knows if/how to do this I'd love if you were to give me the script, and is there any component I have to give to the object?
Why dont you post something you have tried and maybe we can help debug? This is not a community in which will always want to go through the work and make someone a script. You will be lucky to find someone kind enough for that. Ins$$anonymous$$d I can help you debug your script if you post it.
Answer by milky_tunes · Jan 21, 2018 at 11:59 AM
Ah okay, of course I could send it, here it is:
{ { void Update () { comprobarDistancia(); if (walk) Walk (); else if(!walk && !isWaiting){ StartCoroutine(Wait()); }
}
IEnumerator Wait(){ isWaiting = true; animation.CrossFade ("idle"); yield return new WaitForSeconds (5.0f); walk = true; isWaiting = false;
Can you click edit on your post and select all of the code and then click on the '101010' icon. $$anonymous$$akes the code easier to read.
Thats the full code? Seems really incomplete so that is probably where the errors come from.
Answer by WinterboltGames · Jan 21, 2018 at 12:04 PM
You can do the following steps and write the following code and see if it works for you...
STEPS
Create a gameObject in the scene
Add a rigidbody component to it
Add a 2d collider to it (example: BoxCollider2D)
Create a new script call it NpcBehaviour
Write the following code...
CODE using UnityEngine; public class NpcBehaviour : MonoBehaviour { public float speed; public float moveRate; public int dirX; public int dirY; private float moveCounter; private new Rigidbody2D rigidbody2D { get { return GetComponent<Rigidbody2D>() ?? default(Rigidbody2D); } } private void Update () { if (rigidbody2D) { if (moveCounter > moveRate) { ChangeDirection(); moveCounter = 0f; } Vector2 vel = new Vector2(dirX * speed, dirY * speed); rigidbody2D.velocity = Vector2.Lerp(rigidbody2D.velocity, vel, Time.deltaTime * 10f); moveCounter += Time.deltaTime; } } private void ChangeDirection () { dirX = Random.Range(-1, 1); // -1 or 0 or 1 dirY = Random.Range(-1, 1); // -1 or 0 or 1 } }
FINAL STEP 1. Attach the script to the desired game object
Hope this helps!
how woould i make it so that the random range is only between -1 and 1 and not 0?
Your answer