I've been following this Pong tutorial, which is great: https://noobtuts.com/unity/2d-pong-game. The C#, unity components etc I understand. But what I am having trouble with is understanding the logic of how it reverses the direction of the ball depending on where it hits.
I know that what it is doing is condensing a new Y value to -1, 0, 1, via the hitFactor function, which returns that value and then sets that to the new Y (so going up or down) based on the relative ball position to the paddle, divided by the height/size of the paddle. But that's the bit I don't really truly understand, how does that work and why? I have been using Debug.log to send all the different parts of it to try and understand, as well as visually looking in Unity and trying to figure it out from there via the inspector, but I'm just having a mental block. To me I can vaguely see how this code is finding a relative position and then dividing by the height of the paddle to somehow condense it to this range but I'm really just stuck on it in my head.(the hitfactor function itself is basically where I am stuck)
Here's the function:
float hitFactor(Vector2 ballPos, Vector2 racketPos,
float racketHeight) {
// ascii art:
// || 1 <- at the top of the racket
// ||
// || 0 <- at the middle of the racket
// ||
// || -1 <- at the bottom of the racket
return (ballPos.y - racketPos.y) / racketHeight;
}
And in context with the collision:
if (col.gameObject.name == "RacketLeft") {
// Calculate hit Factor
float y = hitFactor(transform.position,
col.transform.position,
col.collider.bounds.size.y);
// Calculate direction, make length=1 via .normalized
Vector2 dir = new Vector2(1, y).normalized;
// Set Velocity with dir * speed
GetComponent<Rigidbody2D>().velocity = dir * speed;
I'm sure this is a very basic thing, but I am struggling with this type of thing. I am on Khan academy, starting from very basic stuff and working my way up, so no doubt maybe when I get to vectors I might understand this more, but I'd like to try and really get my head around this particular issue.
Sorry for the very basic question, I have been dabbling in C# and Unity for a while, but I have realised my weakness is really in the basic core logic of some things....I am a composer by day but I really enjoy trying to get back into this side of my brain, I guess it's super dusty in there hahaha.
Thanks so much in advance for any help, I truly appreciate it.