Hi, i want to add an platform into my app which has an random movement. The Game is an 2D game and the platform should only move on the x-axis. I want that the platform changes its speed and moves random.
So:
The platform is on the x-axis and moves into the positive way of the x-axis. Then it should turn into the negative way and while the platform does this, it should also change its speed.
How can id do this
Here is a bit of code that does it with Transform.Translate. This may not be what you want if you are using the physics engine and want to interact with the platform in a specific way:
#pragma strict
var minSpeed = 0.3; // Range of speeds
var maxSpeed = 1.5;
var minX = -3.0; // Restricts the range of motion
var maxX = 3.0;
var minDuration = 0.5; // Range of time at one speed and direction
var maxDuration = 2.0;
private var speed = 1.0;
private var direction = 1.0;
function Start () {
NewSpeedDir();
}
function NewSpeedDir() {
speed = Random.Range(minSpeed, maxSpeed);
if (Random.Range(0,2) == 0)
direction = 1.0;
else
direction = -1;
Invoke("NewSpeedDir", Random.Range(minDuration, maxDuration));
}
function Update () {
transform.Translate(speed * direction * Time.deltaTime, 0.0, 0.0);
if (transform.position.x > maxX) {
transform.position.x = maxX;
direction = -direction;
}
if (transform.position.x < minX) {
transform.position.x = minX;
direction = -direction;
}
}