Hello. This question might be already answered but I wasn’t able to find a solution for this.
I have an character that already rotates and move. Now I want to make the character to rotate and to walk in the direction he is facing when i press “W” key.
Here is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class moveScript : MonoBehaviour {
public float speed = 1.5f; // The speed that the player will move at.
public float mspeed=1f;
Vector3 movement; // The vector to store the direction of the player's movement.
public Rigidbody playerRigidbody; // Reference to the player's rigidbody.
void Awake ()
{
// Create a layer mask for the floor layer.
// Set up references.
// anim = GetComponent <Animator> ();
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);
// Turn the player to face the mouse cursor.
Turning ();
// Animate the player.
// Animating (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);
}
void Turning ()
{
Vector3 mrotation=new Vector3(0, Input.GetAxis("Mouse X"), 0);
playerRigidbody.transform.Rotate(mrotation* Time.deltaTime * mspeed);
}
/* void Animating (float h, float v)
{
// Create a boolean that is true if either of the input axes is non-zero.
bool walking = h != 0f || v != 0f;
// Tell the animator whether or not the player is walking.
anim.SetBool ("IsWalking", walking);
}*/
}
I know there is a way to do that( so many games already use it) and I really want to get it working on my project.
Any help will be appreciated and I would like to thank you in advance
Serju