X-axis changing instead of Z, after rotating the Gameobject 90degrees on y-axis

Im making a game, where you can controll an object by writing commands like: ,forward_1" and it makes the object move forward 1 meter, but when I tried rotating the object, the blue arrow for the Z axis was pointing at the right direction and the object moved in the desired direction, but the code that makes the object stop after this 1 meter, didn´t work, because the value of the x axis was changing, even though I rotated the object local on its Y axis for 90 degrees! AND I also tried it with global, didn’t work either.
Here is the code:

if (float.TryParse(turnDirection[1], out float value))
{
    UnityEngine.Debug.Log("rotated Object");
    Quaternion currentRotation = transform.rotation;
    currentRotation.y = value;
    transform.localRotation = currentRotation;
}

This rotates the Object, everything’s working fine with that.^

if (forward)
{
    transform.Translate(Vector3.forward * speed * Time.deltaTime);
}

This makes the object go forward, if forward is active.^

if (transform.position.z > (currentLocation + distance) && forward == true)
{
    forward = false;
}

This sets forward to false, as soon as the transform.position.z is bigger than the starting position(currentLocation) + the distance (the number of meters given in the command: forward_1). This how ever, doesn’t work, because after rotating, the X axis still changes, so transform.position.z will never be bigger than the desired location… Does this have something to do with the local and global rotation?

1 Answer

1
  1. Your mixing local space with global space in the rotation code. You should stick with one space to work with. Probably you want transform.rotation.

  2. But, your setting the components of a Quaternion in code??? That is very unusual. That is not recommended unless the user fully understands Quaternions. You probably want to use transform.Rotate instead. IF you ran your rotate code a few times, you might find it stops working after a while.

Thanks! I forgot transfrom.Rotate was a thing. And I was stupid XD I didnt realize that I only used the localRotation in: transform.localRotation = currentlocation, I should have added it everywhere. Works now! Thank you very much! U made my day :)

–