Question by
ProsaicStudios · May 28, 2016 at 09:10 PM ·
movementenemy2d-physics
Enemy Movement With Physics (2D)
I'm trying to create enemy units that float around on a 2D plane. The script I have below makes the enemy object move, but instead of floating around, it is jumping from one spot to another. Additionally, it is not properly colliding with objects. For example, instead of hitting a wall, it is going on top of it. Any help would be much appreciated.
If you are having trouble envisioning the movement I am trying to achieve, take a look at the UFO in this tutorial: https://unity3d.com/learn/tutorials/projects/2d-ufo-tutorial/introduction-2d-ufo-project?playlist=25844
using UnityEngine;
using System.Collections;
public class DogMovement : MonoBehaviour {
public float moveSpeed;
private Rigidbody2D rb2d;
private bool moving; //???
public float timeBetweenMove;
private float timeBetweenMoveCounter;
public float timeToMove;
private float timeToMoveCounter;
private Vector3 moveDirection;
// Use this for initialization
void Start () {
rb2d = GetComponent<Rigidbody2D> ();
timeBetweenMoveCounter = timeBetweenMove;
timeToMoveCounter = timeToMove;
}
// Update is called once per frame
void Update () {
if (moving) {
timeBetweenMoveCounter -= Time.deltaTime;
rb2d.velocity = moveDirection;
if (timeBetweenMoveCounter < 0f) {
moving = false;
timeBetweenMoveCounter = timeBetweenMove;
}
} else {
timeBetweenMoveCounter -= Time.deltaTime;
rb2d.velocity = Vector2.zero;
if (timeBetweenMoveCounter < 0f) {
moving = true;
timeToMoveCounter = timeToMove;
moveDirection = new Vector3 (Random.Range (-1f, 1f) * moveSpeed, Random.Range (-1f, 1f) * moveSpeed, 0f);
}
}
}
}
Comment