- Home /
How to move character X and Z axis?
I have my code that randomly moves my NPC around. Currently my monster only moves left and right on the X axis, but I want the monster to randomly move via the X and Z axis. Thank you for any help!
 public class Walking : MonoBehaviour {
 private float latestDirectionChangeTime;
 private readonly float directionChangeTime = 3f;
 private float characterVelocity = 2f;
 private Vector3 movementDirection;
 private Vector3 movementPerSecond;
 
 
 void Start(){
     latestDirectionChangeTime = 0f;
     calcuateNewMovementVector();
 }
 
 void calcuateNewMovementVector(){
     //create a random direction vector with the magnitude of 1, later multiply it with the velocity of the enemy
     movementDirection = new Vector3(Random.Range(-1.0f, 1.0f), 0,Random.Range(-1.0f, 1.0f)).normalized;
     movementPerSecond = movementDirection * characterVelocity;
 }
 
 void Update(){
     //if the changeTime was reached, calculate a new movement vector
     if (Time.time - latestDirectionChangeTime > directionChangeTime){
         latestDirectionChangeTime = Time.time;
         calcuateNewMovementVector();
     }
  
     //move enemy: 
     transform.position = new Vector3(transform.position.x + (movementPerSecond.x * Time.deltaTime), 22.45f,
         transform.position.z + (movementPerSecond.y * Time.deltaTime));
     
 
 }
 }
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by j4ke · Feb 14, 2020 at 01:53 PM
The problem is that you change the value transform.position.z with the value movementPerSecond.y. The value movementPerSecond.y will always stay 22.45f in the Update function. This could work:
   //move enemy: 
      transform.position = new Vector3(transform.position.x + (movementPerSecond.x * Time.deltaTime), 22.45f,
          transform.position.z + (movementPerSecond.z * Time.deltaTime));
Your answer
 
 
             Follow this Question
Related Questions
X axis, y u no work? 2 Answers
Disable Diagonal Move 2 Answers
Blurry movement problem 0 Answers
Rigidboy.velocity with integer? 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                