- Home /
How to change direction without changing speed?
Hi I am absolute beginner to unity, I want to change direction and position of moving player on mouse click.. I tried following..
void FixedUpdate(){
if(transform.position.x > screenBoundries.x-objectWidth || transform.position.x < -screenBoundries.x+objectWidth){
directionX = -directionX;
}
if (transform.position.y > screenBoundries.y-objectHeight || transform.position.y < -screenBoundries.y+objectHeight){
directionY = -directionY;
}
transform.position += SPEED*Time.deltaTime * (Vector3) new Vector2(directionX,directionY);
if (Input.GetMouseButtonDown(0)){
newPosition();
newDirection();
}
}
void newDirection(){
directionX = Random.Range(-1.0f, 1.0f);
directionY = Random.Range(-1.0f, 1.0f);
}
void newPosition(){
positionX = Random.Range(-screenBoundries.x+objectWidth, screenBoundries.x-objectWidth);
positionY = Random.Range(-screenBoundries.y+objectHeight, screenBoundries.y-objectHeight);
transform.position = new Vector2(positionX,positionY);
}
but the speed is not constant after each click , it varies as Random.Range(-1.0f, 1.0f) changes the direction.. any solution, Previously I was on Godot and this logic was working there..
Answer by Snipe76 · Jan 02, 2019 at 06:50 PM
Instead of changing the position directly, use transform.Translate(). it is much better and smoother for movement.
Because the direction affects the speed (because its a vector) you need to normalize it in order to gain constant speed.
new Vector2(directionX,directionY).Normalize();
and that will give you a direction with constant speed.
here is more info about transform.Translate()
Unity Help-transform.Translate
More about Normalize:
Your statement about Translate() being "smoother" could be misunderstood. It sounds like you mean the movement is smoother which would be wrong. Do you mean it's more convenient? There's nothing wrong with setting transform.position directly in this case.
Also, I think you mean .normalized
The Normalize() method is used on variables: myDirection.Normalize();