How can I smooth out 2D object movement?
Hello, I am a VERY new developer, so I apologize if this is a basic question, but I have scoured the site for an answer and cant seem to find the solution.
I am trying to create an enemy script that will have the enemy walk around randomly, which I have sort of accomplished, but he snaps around to each random position instead of smoothly moving to the position. I have tried several iterations with lerp and transform and translate, but nothing seems to work!
Here is the closest I have come so far:
public class EnemyBehavior : MonoBehaviour {
public float Speed;
private Rigidbody2D rb2d;
void Start() {
rb2d = GetComponent<Rigidbody2D> ();
StartCoroutine(Wait());
}
private IEnumerator Wait() {
float randomX;
float randomY;
randomX = Random.Range (-1, 2);
randomY = Random.Range (-1, 2);
Vector2 movement = new Vector2 (randomX, randomY);
rb2d.MovePosition (rb2d.position + movement * Time.deltaTime * Speed);
yield return new WaitForSeconds(2f);
StartCoroutine(Wait());
}
}
This code will make the enemy move to a new position within 1 tile every 2 seconds. The problem is he just "appears" there and I want it to seem smooth like he is walking.
Any help would be greatly appreciated!
hi, check this it might be helpful :)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class health$$anonymous$$anager : $$anonymous$$onoBehaviour {
private Rigidbody2D rb2d;
void Start() {
rb2d = GetComponent<Rigidbody2D> ();
StartCoroutine(Wait());
}
private IEnumerator Wait() {
rb2d.velocity = new Vector2 (UnityEngine.Random.Range(-1,2),UnityEngine.Random.Range(-1,2));
yield return new WaitForSeconds(2f);
StartCoroutine(Wait());
}
}
Your answer
Follow this Question
Related Questions
Grid Movement with Smooth Movement 0 Answers
How do I assign a velocity to an object on only 1 axis? 1 Answer
Unity 2D Enemy movement problems 2 Answers
2D Change direction with an arc 1 Answer