Today we talked about how to get the ball to follow along with the paddle until the start of the game. We didn’t get all the way, but we got most of the way. Here are the steps we talked about needing to do:
- At the start, the ball should follow along with the paddle
- maintain the same relative position
- When the user clicks the button, it should release the ball
So, to manage the first of these, we need to start out knowing the distance between the paddle and the ball. We’re going to do all this work in a script attached to the ball. It is going to need to know things about the paddle. The easiest way to do this is to have a public variable called paddle. The type of that is going to be the same as the class name you gave the paddle’s script. Mine is “mouseControl”.
So in the ball script, after the class declaration, you want something like:
public mouseControl paddle;
Then in Unity you’re going to need to drag the paddle into that portion of the ball’s Inspector to link the paddle to the ball’s script.
You also will need variables to hold the difference in position between the ball and the paddle at the start of the game. Those don’t need to be public, but they do need to be global. Under the line of code above, I added the following to declare two float variables called offsetX and offsetY:
float offsetX, offsetY;
So, in void Start(), you want to calculate that difference.
offsetX = this.transform.position.x – paddle.transform.position.x;
I’ll let you figure out the offsetY code — it’s quite similar.
Then, in Update, you want to follow the paddle with every frame, plus the offsets. I like to separate out the pieces to avoid a long line of code, so I create a couple new floats and then create the new Vector3 using those.
float newX = paddle.transform.position.x + offsetX;
float newY… (I’ll let you figure that one out, too.)
Then you set the new position.
this.transform.position = new Vector3(newX, newY);
And that should have them flying along together. It breaks the game overall, so check back for the next step next week.