- Home /
Unity 2D Random Movement
Hi everyone, I'm simply trying to make a ball move in random directions (and bounce off the sides of the walls), and this is my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyEasyAI : MonoBehaviour {
public Rigidbody2D rb;
public float speed = 1;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D> ();
}
void FixedUpdate(){
Vector2 Movement = new Vector2 (Random.Range(-1, 1), Random.Range(-1, 1));
rb.AddForce (Movement);
print (Movement);
}
}
However, what happens whenever I execute the script is that the gameobject simply moves down and to the left, and then stays put at the corner (the corner of the wall where it is being blocked by the colliders). How can I edit it so that the ball moves in a random and sporadic fashion? Any help would be appreciated.
Answer by FlaSh-G · Jun 23, 2017 at 11:39 AM
I'd try setting a random direction every 1-2 seconds or so and then stay with that, and apply force in that direction, until you change it again. If you randomize every (fixed) frame, you don't have enough time to accelerate.
public float accelerationTime = 2f;
public float maxSpeed = 5f;
private Vector2 movement;
private float timeLeft;
void Update()
{
timeLeft -= Time.deltaTime;
if(timeLeft <= 0)
{
movement = new Vector2(Random.Range(-1f, 1f), Random.Range(-1f, 1f));
timeLeft += accelerationTime;
}
}
void FixedUpdate()
{
rb.AddForce(movement * maxSpeed);
}
Note that I replaced the ints in the Random.Range calls with floats so you can get anything between -1 and 1 instead of just -1, 0, or 1. Your choice, of course.
Thank you so much! I was trying to make a tornado projectile, and this was perfect for it!
Thank you so much for this script. i've been trying to make/find one for at least two months now and this works PERFECTLY. Again, thank you.
Your answer
Follow this Question
Related Questions
2d obstacle moving up and down question 1 Answer
Random Movement in 2D 2 Answers
How to create random movement in 2d 2 Answers
Random movement direction cycle. 2 Answers
Random Movement : 2d 1 Answer