- Home /
How can i make diagonal movement?
I dont know how make diagonal movement im very new in this and a frind give me this code i have an idea of how it works but im not completley sure can someone help me to make a diagonal movement?
public class Player : MonoBehaviour {
 private Rigidbody rb;
 private Vector3 verticalVelocity;
 public float speed;
 private Vector3 velocity;
 
 void Start() {
     rb = GetComponent<Rigidbody>();
 }
   
 void Update()
 {
     if (Input.GetAxis("Vertical") != 0) MovementVertical();
     if (Input.GetAxis("Horizontal") != 0) MovementHorizontal();
  
 }
 public void MovementVertical()
 {
     verticalVelocity = this.transform.forward * speed * Input.GetAxis("Vertical");
     verticalVelocity.y = rb.velocity.y;
     rb.velocity = verticalVelocity;
 }
 public void MovementHorizontal()
 {
    verticalVelocity = this.transform.right * speed * Input.GetAxis("Horizontal");
     verticalVelocity.y = rb.velocity.y;
     rb.velocity = verticalVelocity;
 }
     
}
by the way thanks for the help
Answer by BluesyPompanno · Jul 09, 2018 at 08:06 PM
You shoudln't be specifying movement in all directions in different functions/methods .
You could try this.
  public float speed = 6f;            // The speed that the player will move at.
     Vector3 movement;                   // The vector to store the direction of the player's movement.
     Rigidbody playerRigidbody;          // Reference to the player's rigidbody.
 
     void Awake ()
     {
         playerRigidbody = GetComponent<RigidBody>();
     }
 
 
     void FixedUpdate ()
     {
         // Store the input axes.
         float h = Input.GetAxisRaw ("Horizontal");
         float v = Input.GetAxisRaw ("Vertical");
 
         // Move the player around the scene.
         Move (h, v);
     }
 
     void Move (float h, float v)
     {
         // Set the movement vector based on the axis input.
         movement.Set (h, 0f, v);
         
         // Normalise the movement vector and make it proportional to the speed per second.
         movement = movement.normalized * speed * Time.deltaTime;
 
         // Move the player to it's current position plus the movement.
         playerRigidbody.MovePosition (transform.position + movement);
     }
 }
Your answer
 
 
             Follow this Question
Related Questions
Slowly move a GameObject on 1 axis, then destroy it. 1 Answer
Move Character to touched Position 2D (Without RigidBody and Animated Movement) 1 Answer
How do I make GameObject actions ease in and out 1 Answer
How can I drag a GameObject along a fixed line? 2 Answers
How can i make it so that the object doesnt instantly go to top speed. Here is my code 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                