Does a Character Controller script override the physics in Unity?

I am asking this as I set out to prototype an idea I had for a game. I created some simple blocks on a 3d plain and then attached a box collider to the cubes to prevent the player going through them only this didn’t work. So would the Player controller script below override the colliders I put on the blocks to be walls?

Thanks.

‘’'
public class PlayerMovement : MonoBehaviour {

Vector3 PMove;

void Start () {
	PMove = transform.position; 
}

void Update () {

	if (Input.GetKey(KeyCode.W)) {
		PMove.x += 1f;
		Debug.Log("w key pressed");
	}

	if (Input.GetKey(KeyCode.A)) {
		PMove.z += 1f;
		Debug.Log("a key pressed");
	}

	if (Input.GetKey(KeyCode.S)) {
		PMove.x -= 1f;
		Debug.Log("s key pressed");
	}

	if (Input.GetKey(KeyCode.D)) {
		PMove.z -= 1f;
		Debug.Log("d key pressed");
	}

	transform.position = PMove;
}

}
’’’

The code below solved it. I think my adding or taking away 1f when moving caused the colliders to be ignored.

‘’'
public class PlayerController : MonoBehaviour {

public float speed = 20f;

void Update () {
	if (Input.GetKey(KeyCode.W)) {
	transform.position += Vector3.forward * Time.deltaTime * speed;
	} else if (Input.GetKey(KeyCode.S)) {
	transform.position += Vector3.back * Time.deltaTime * speed;
	}

	if (Input.GetKey(KeyCode.A )) {
	transform.position += Vector3.left * Time.deltaTime * speed;
	} else if (Input.GetKey(KeyCode.D)) {
	transform.position += Vector3.right * Time.deltaTime * speed;
	}

}

}
’’’

Hi, I just want to explain why your previous code was not working.

in your Update function, you modify the value of PMove and then update the transform.position with the value of PMove. However, you’re not starting your update function with something like this

PMove = transform.position

So what happens is that you assume that your transform.position will not be modified between each frame. That assumption is wrong, because the physics engine will modify transform.position.

So it’s not because you were doing incremental changes (even though your new code is already a bunch better), but solely because you were explicitly overriding the transform.position with the value of PMove

Thank you for explaining that to me. For someone like myself learning how to code that is very helpful. Appreciate you taking the time to reply. :smiley:

Privacy & Terms