简体   繁体   中英

Building pong in Monogame, but balls won't interact with player 1 paddle

I'm pretty new to programming. Basically just finished up a couple tutorials and barebones instructions. I wanted to code pong to get myself started trying to do stuff on my own, but I've hit a bit of a snag. For some reason the ball I generate won't interact with my player 1 paddle at all, but it will interact with my player 2 paddle completely. I can't seem to figure out why since I basically used the exact same code twice just correcting for differences in controls and positions, so any help would be much appreciated. My code for the interaction between the ball and the paddles is as follows:

 ballPos += ballSpd * (float)gameTime.ElapsedGameTime.TotalSeconds;

 if (ballPos.X == plyr1Pos.X && ballPos.Y + 3 > plyr1Pos.Y - 25 && ballPos.Y - 3 < plyr1Pos.Y +25)
 {
     ballSpd.X = 150;
     ballSpd.Y = 0;
 }

 else if (ballPos.X == plyr2Pos.X && ballPos.Y + 3 > plyr2Pos.Y - 25 &&  ballPos.Y - 3 < plyr2Pos.Y + 25)
 {
     ballSpd.X = -150
     ballSpd.Y = 0;
 }

I understand there is probably a more efficient way of doing this, but like I said I'm still really new to this and want to learn more, so any constructive criticism is welcome.

Depending on the precision of TotalGameSeconds, the ball might never "hit" the paddle (ballPos.X < plyr1Pos.X). To fix this, try modifying your X detection like so:

 if (ballPos.X <= plyr1Pos.X && ballPos.Y + 3 > plyr1Pos.Y - 25 && ballPos.Y - 3 < plyr1Pos.Y +25)
 {
     ballSpd.X = 150;
     ballSpd.Y = 0;
 }

 else if (ballPos.X >= plyr2Pos.X && ballPos.Y + 3 > plyr2Pos.Y - 25 &&  ballPos.Y - 3 < plyr2Pos.Y + 25)
 {
     ballSpd.X = -150
     ballSpd.Y = 0;
 }

Now it will detect if the ball goes "beyond" the paddle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM