We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi there, do you have a more elegant solution to this?:
void show(String side){
if(side == "right"){
rect(rPx, rPy, paddleWidth, paddleHeight);
rPy += yspeed;
}
if(side == "left"){
rect(lPx, lPy, paddleWidth, paddleHeight);
lPy += yspeed;
}
}
Depending on the parameter the rectangels should be on the left or right side. It's working just fine, I just don't feel like it's nice code...
Answers
You say "solution to this." Solution to what? What do you want the code to do? Be specific.
You are only showing part of your code, but it looks like you are using a combination of an argument (String side) and hard-coded global variables (rPX / lPX) to create your different pong paddles. That doesn't necessarily make sense. Is this a method of a class/object? Is it just a function? More detail would help. There are many ways of approaching related problems.
side is a String object, comparing using == won't work. see String in the reference.
Probably you need to draw both rects anyway, so no use to use
if
in the first placeJust draw both
That's factually false, and you should know better! He's even stated it's working! 3:-O
In Java, both
==
and!=
operators use the actual value stored in a variable. ~O)So at
side == "right"
, if the value stored in variable side is the same value of object "right", it evals astrue
, otherwise asfalse
. :-BNotice that Java caches all
""
String literals found in our programs.As long as variables are assigned from String literals, it is relatively safe to use operators
==
and!=
for comparing between them. :ar!Of course, we shouldn't rely on that Java's String cache feature.
Always using String:equals() method is the safe game. ;;)
Im using this method in a class. I then create 2 objects of that class(left and right paddle) and call the method show(string side) within the draw() method:
rP for rightPaddle and lP for left Paddle... I know using a class and objects this way doesn't make much sense but when I simply set all variables I need as global variables and then draw the rectangles it doesn't work properly. By using the same variables the rectangles are like 1/10 the size and are both at the upper left corner. By putting all the variables in a class it just works fine for some reason...void draw(){ background(0); rP.show("right"); lP.show("left"); }
your approach is very wrong
this is how it should look like:
and
The idea of a class is that each object derived from it works separately
Please look at the tutorial about objects
https://www.processing.org/tutorials/objects/
Post your entire code to get real help
This is better.
Rule of thumb: Put as much as you can into the class but only for ONE paddle.