-
Random movement of a sprite in 2D
over 8 years ago
-
about 8 years ago
Awesome!
-
-
about 2 years ago
Thank you for your script. (I'm new). I'm making a 2D top down game and I need to randomly move mobs like minecraft. Your script works but flips the character x-axis by -90, photo in appendix to the letter. Please help me with this problem. sorry for my English https://drive.google.com/file/d/1zT8tjV_XmXfCw7uBciMRpneq5yJpcrII/view?usp=sharing - bug picture -
-
over 3 years ago
This is my solution for circle random movement:
using System.Collections; using UnityEngine; public class RandomMove : MonoBehaviour { public float moveSpeed; Vector3 target; public float SpeedOfChangingTarget = 5; private float camHeight; private float camWidth; private float circleRadious = 2; SpriteRenderer spriteRenderer; void Start() { Camera cam = Camera.main; camHeight = 2f * cam.orthographicSize; camWidth = camHeight * cam.aspect; spriteRenderer = GetComponent<SpriteRenderer>(); InvokeRepeating("GenerateNewTarget", 0f, SpeedOfChangingTarget); } void Update() { circleRadious = spriteRenderer.bounds.size.x / 2; Vector3 currentPos = transform.position; if (currentPos == target) { GenerateNewTarget(); } transform.position = Vector3.MoveTowards(currentPos, target, Time.deltaTime*moveSpeed);//movement from current position to target position } void OnCollisionStay2D() { GenerateNewTarget(); } void GenerateNewTarget() { target = new Vector3(Random.Range(-(camWidth/2-circleRadious), camWidth/2-circleRadious), Random.Range(-(camHeight/2-circleRadious), camHeight/2-circleRadious), 0); //again provide random position in x and y } }
-
-
about 8 years ago
Thank you very much, it was much useful
-
4 Comment(s)