[QUESTION] Movement of paddle via arrow keys

Respectfully request how one would change movement for the paddle with arrow keys. Utilizing the movement for laser defender, I tried the following code below but without the camera set to the world space (something I didnt like because it threw everything off for me) I did this.

public float speed = 10.0f;
    void MoveWithArrows () {
	Vector3 paddlePos = new Vector3 (0.5f, this.transform.position.y, 0f);
	if(Input.GetKey(KeyCode.LeftArrow)) {
		transform.position += new Vector3(-speed * Time.deltaTime, 0,0);
		} 
	else if (Input.GetKey(KeyCode.RightArrow)) {
		transform.position += new Vector3(speed * Time.deltaTime, 0,0);
		}
	this.transform.position = paddlePos;
}

This just makes it stuck on the left side of the screen. I know I would have to also add in a clamp mathf too i assume I would have to set that via the paddlePos. Any help is appreciated.

Hello @Joshua_Jahwun_Whitma, how are you?

The problem here is that you are changing the position back to paddlePos after changing it with the rightarrow or leftarrow. You don’t have to use paddlepos here, although you will need a clamping mechanic, either using a mathf.clamp or manually adding it to the if. Example:

[code]public float speed = 10.0f;
void MoveWithArrows ()
{
if(Input.GetKey(KeyCode.LeftArrow) && transform.position.x >= minX)
{
transform.position += new Vector3(-speed * Time.deltaTime, 0,0);
}
else if (Input.GetKey(KeyCode.RightArrow && transform.position.x <= maxX))
{
transform.position += new Vector3(speed * Time.deltaTime, 0,0);
}

}[/code]

Unfortunately this didn’t work. Issues with the && and I can’t find any documentation with it.

I forgot to add a parentheses at the second if, after the input.getkey(keycode.rightarrow

Privacy & Terms