- Home /
Player moving automatically in 3D
I have just started learning unity. I am working on a 3D game. I have created a player gameobject from a capsule. I have added a Player.cs and LookX.cs script to the player gameobject, these control the movement from keyboard and horizontal mouse movement.
I have created an empty gameobject called LookY and added it inside player gameobject and i added the Main camera inside this LookY Gameobject.
I have attached the LookY.cs script to the LookY gameobject. When game starts, i move the mouse perfectly fine and walk around fine but i continuously keep moving in one direction slowly even i haven't pressed any buttons,
I suspect the player.cs to have the fault but no errors show up.
How can i stop it from moving on its own. Also the player was moving in reverse so i set the y axis rotation of main camera to 180.
Since i can attach only 1 file, i am writing all scripts in 1 file attached below.
Answer by faisalshakeelkhan · Aug 02, 2019 at 09:26 AM
This is the player.cs code :
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Player : MonoBehaviour { //used to control player movement private CharacterController _controller; //player movement speed [SerializeField] private float _speed = 3.5f;
private float _gravity = 9.81f;
void Start()
{
//getting access to player
_controller = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
CalculateMovement();
}
void CalculateMovement()
{
float horizontalmovement = Input.GetAxis("Horizontal");
float verticalmovement = Input.GetAxis("Vertical");
//Y is zero as it controls our jumping movement and Z controls forward and backward
Vector3 direction = new Vector3(horizontalmovement, 0, verticalmovement);
//player speed and direction
Vector3 velocity = direction * _speed;
velocity.y -= _gravity;
//this transforms local space to world space
//local space values to be converted to world space so player can correctly move w.r.t the camera movement
velocity = transform.transform.TransformDirection(velocity);
//applying gravity on y axis of player.
_controller.Move(velocity * Time.deltaTime);
}
}
I can't see why it would be constantly moving here :/ Try checking the Input vars using this
Debug.Log(direction);
Thanks for taking the time to reply to this.
I removed all scripts and game objects and started doing it from scratch again, now it is working fine,
The reason I assume is that when I added the LookY gameobject inside Player, I didn't set it to 0,0,0 relative to the player.
Your answer
Follow this Question
Related Questions
Best tutorial for movement programing? 1 Answer
3d Space Movement 1 Answer
Locking movement to one axis only (3D game) 1 Answer
Object's vectors are not moving with the object, what did i do wrong? 1 Answer
How to add platform motion to player controller without parenting? - Mostly working code 1 Answer