[solution] Moving paddle through the screen

I was not happy with the behavior of the paddle in the lecture series. In my game I wanted to move my paddle through the screen. It should behave in such a way that if it passes the edge, an equal sized of the paddle appears on the other side (see print screen). Also I want this to be independent of the paddle size so that in later development stages items that increase or decrease paddle size can be added.

Now how to solve this? Try it yourself!

The first thing you should realise that you need to get rid of the mouse position all together. If you control your game with the mouse it would be counterintuitive for the paddle to appear on the right after moving your mouse to the left outside of the playing field. This is especially so since the paddle would move jump back to the left once your mouse would enter the screen on the left side. I replaced the mouse input with simple keyboard input. I lazily copied code I found on the web. (It is important you use the (Input.GetKey) function since this returns true as long as the key is pressed, rather than just once every keypress (as is the case with the Input.GetKeyDown function)).

Ok, so you get your paddle to move on keypresses. What is next? Well we don’t want to clamp our paddle. We want it to move freely and happily over the edges of the playing area. So let’s comment out or delete the clamp function.

Now, the easiest way to make the paddle appear on the other side of the screen is by simply make it appear as if it does. To do this I used three paddles each at exactly a gamespace (16 units) apart. My player paddle is in the start of the game at x=8, my leftDuplicate has an x = - 8 and my rightDuplicate has a x of 24. Because all these paddles have the same script attached they all move simultaneously when I press a keybutton. A new paddle swoops into view as the other one is leaving!

At this stage I congratulated myself, had a beer. Thanked my rubber duck for all it’s support and turned off my computer. The next day when I showed the behaviour to my friend I realised I made a grave mistake. The behaviour is as we want, unless we move too much to either the left or right side, since we run out of paddles! Oops!

The easiest solution would be to simply copy 50 more paddles in the game and hope the player will not move to one side continuously and will hence never notice. But this solution is ugly for it requires the engine to calculate the position of 50 paddles every frame.
Instead I decided to stick with 3 paddles but to hop them over. If you keep moving to the left my most left paddle simply jumps two game spaces to the right.

I know it is a small achievement, but I am very happy with the way it looks and works :). So I wanted to share (see code below).

1 Like

Privacy & Terms