Mathf.Clamp problem

Hello, here is my code:

public void PlayerMovement(){
		float playerSpeed = 10.0f;
		v = Time.deltaTime * playerSpeed * Input.GetAxis("Mouse X");
		transform.Translate(v, 0, 0);
		transform.position = new Vector3(Mathf.Clamp(Time.time, -4.0F, 4.0F), 0, -12);
	}

When playing, the player object goes from left to right, and it wont move when I move the mouse. That happens since I added the last line. Is there any problem with it?

transform.Translate moves the object relatively to its previous position in the world, but the following transform.position sets its absolute position it the world. So the last line overrides the previous one.

Try to swap the lines.

Did that, and now when I start the game the player goes to right and when I move the mouse it moves it a bit, and then the player goes back at the point it were before of it.

I don’t understand why you want to use both Translate and Position at the same time. You should probably use one or the other, not both.

EDIT: just to clarify: you keep overriding the object’s X coordinate each time with that Mathf.Clamp(Time.time, -4.0f, 4.0f). What is the point of this if you are translating the object separately?

I would agree with FizixMan here, I don’t really understand what you’re trying to do here.
Also, why do you clamp Time.time between -4.0f and +4.0f (apart from keeping it smaller than 4.0f as it is a positive value) ?

What Im trying to do is something like in the Invaders game. I move the player with the mouse and I dont want to let him go out the screen

EDIT: I havent ever used Mathf.Clamp ever since now so sorry if I did something wrong

Then I would suggest you clamp your position.x between -4.0f and 4.0f instead of the Time.time variable. This way, you will translate your character with your “Translate” line, and check x value with the Clamp function of the “position” line.

EDIT: The Mathf.Clamp function clamps the first parameter given between the 2 others. Here you were trying to clamp a variable that is read-only. The idea is good, it was just not the good value to clamp :wink:

Hey that worked great thanks!