- Home /
Random Movement : 2d
Hello Everyone..
I am making 2D space shooter kind of game and in that i have scene with x-y plane.
Here i am translating my enemy object in y direction from top to bottom.. But i want my object to change direction after crossing some random distance means i want my object to move left or right diagonally after some random distance..
But i am not getting the way to perform this behavior as i know how to translate object diagonally..
Code which i used is here :
whatWayToGoInLife = Vector3.left * amttomove;
whatWayToGoInLife = whatWayToGoInLife + Vector3.down * amttomove;
transform.Translate(whatWayToGoInLife , Space.World);
But main problem is after crossing some distance on y axis i want my object to move in random direction..
Pleaze someone give me idea..
Thanks in advance for your support and help..
Answer by robertbu · May 31, 2013 at 05:35 AM
One way is to use Random.insideUnitCircle. I'm assuming your character is walking on the X/Z plane. Random.insideUniytCircle returns a Vector2, so you will need to covert it to a Vector3 to use as a direction. When you want to change directions, you redefine the movement vector:
Vector2 v2 = Random.insideUnitCircle;
direction = new Vector3(v2.x, 0.0f, v2.y);
And you code for movement might look like:
transform.Translate(direction * speed * Time.deltaTime, Space.World);
hmm i have written code :
function Update () {
var amttomove : float = currentSpeed * Time.deltaTime;
if(transform.position.y <= -6.00f)
{
//SetPositionandSpeed();
}
if(transform.position.y <= 1.00f)
{
SetRandomPosition();
transform.Translate(direction * amttomove, Space.World);
}
else
{
transform.Translate(Vector3.down * amttomove , Space.World);
}
}
function SetPositionandSpeed()
{
currentSpeed = Random.Range($$anonymous$$Speed , maxSpeed);
x = Random.Range(-3.5f , 3.5f);
z = -6.72f;
y = 8.0f;
transform.position = new Vector3(x , y , z);
if(gameControllerScript.gameStarted)
scoreControllerScript.$$anonymous$$anageEnimies();
}
function SetRandomPosition()
{
var v2 : Vector2= Random.insideUnitCircle * 2;
direction = new Vector3(v2.x, v2.y, 0.0f);
}
But this is not correct as function is being called on each frame.. so how do i make my player to move after crossing some y distance ? should i use timer or calculate y distance??
You could structure it like this:
private var direction = Vector3.down;
private var newDirection = false;
function Update () {
var amttomove : float = currentSpeed * Time.deltaTime;
// if(transform.position.y <= -6.00f)
// {
//SetPositionandSpeed();
// }
if(transform.position.y <= 1.00f && !newDirection)
{
SetRandomDirection();
newDirection = true;
}
transform.Translate(direction * amttomove, Space.World);
}
function SetRandomDirection()
{
var v2 : Vector2= Random.insideUnitCircle * 2;
direction = new Vector3(v2.x, v2.y, 0.0f);
}
Note I've changed the name of your function, since this code sets a direction, not a position. Also look how direction is initially set to Vector3.down.