Unity Game Dev : create a Player Bounds with “if statement”! (Part III)
Ok, now we are ready to create Player Bounds!
What’s the logic behind?
We want our Player go to the right and when it arrive at this position
(we say 11.25 float on positive X axis)
it appear to the left, and when it arrive at -11.25 float it appear to the right, ok?
This is the the logic in pseudocode
In code, we made this
Create an IF statement, set the condition, and if the condition is true, run the code
I explain what happen here :
in the IF we said : “Ehi, check my position on X axis”
IF this is true, so if my position on X is MAJOR OR EQUAL to 11.25f,
my position is now a NEW POSITION, or NEW VECTOR3, where my X axis is now at -11.25f.
Try and see if works!
Everythings seems ok! BUT, we have a little bug
If I made this
You see? Even if i’m a little below it appear again at middlescreen.
Why this?
Because when we RESET the position with “NEW VECTOR3 POSITION”, we change the X axis, and it works, but at the OTHER TWO AXES we give a wrong position. Think wisely : when Player pass the screen, we need to change ONLY the X AXIS, but Y and Z REMAIN THE SAME.
Now the question is : how can I pass the ACTUAL position to the Player?
That’s when the TRANSFORM component comes to help us!
That component check our posiotion CONSTANTLY, so to pass our ACTUAL POSITION on Y and Z AXES, we simply pass
transform.position.y and transform.position.z!
If we try now
But we’re not finish yet.
We need the same thing from left to right!
And the logic is exactly the same, BUT WATCH OUT!
You see the difference?
In this case, we check the NEGATIVE VALUE, so the logic inside the IF is
“Ehi, check if my position on X is MINOR OR EQUAL to -11.25”
I tell you this because sometimes can be happen to COPY / PASTE code, expecially in the beginning for make things fast or just because we make a test right?
Even if is not a great problem, I raccomend to NOT MAKE THAT.
At least, not at beginning. We have to use our brain, and logic, and write again a little piece of code is not a great problem guys!
So, our code is now this
So now we are ok from left to right and right to left, we miss the part where Player can go up only to middle screen and it blocks, ok?
The best part here is : where you UNDERSTAND THE LOGIC, the rest is the same, even if we have to chenge little pieces!
Again, check the position in the IF STATEMENT
and if is true, run the code!
We check the Y axis, if is MAJOR OR EQUAL to 0, set the Y value to 0, and the rest remain at same position.
Same for down Y, because we don’t want the Player go down out of the screen!
We need to block it.
And again, easy to do with same line of code and good attention
And if we press Play
Everythings works as we want! Great!!
In the next section we clean up our code!