Question

So I have the following code expressing the "AI" movement. pdl_R is the AI paddle, AIH is AI Height, AIHS is AI Height Speed. I want the code to move the paddle by AIH in the direction of AIHS.

pdl_R.y=AIH;
AIH+=(3*AIHS);  
if(pdl_R.y==stage.stageHeight || pdl_R.y==stage.stageHeight-pdl_R.height)
{
    AIHS*=-1;
}

But when the pdl_R (the AI paddle) reaches the bottom of the screen (down is the default direction), it stays there and flickers up and down by 3 pixels (instead of the expected direction switch).

My initial AIH is 200 and my initial AIHS is 1.

Was it helpful?

Solution

When your AIH reaches stage.stageHeight, the following happens:

  1. Y is assigned stage.stageHeight (==AIH)
  2. AIH is incremented by 3*AIHS (==3, assuming AIHS==1, although the actual value of AIHS doesn't matter, only its sign does). Therefore your paddle actually moves 3 pixels more than you want.
  3. You check the condition, it's true, so AIHS=-1*AIHS. AIHS is now -3.
  4. Okay, next frame, Y is assigned AIH (==stage.stageHeight+3), AIH is incremented by AIHS, and is now equals stage.stageHeight again. Checking condition is false, no change to AIHS. Paddle is now moving upwards.
  5. Next frame, Y is assigned AIH that equals to stage.stageHeight, but the paddle is now moving upwards! So, when you again check for your condition, AIHS reverts to +3. And, AIH is already stage.stageHeight-3, so 2 frames further the cycle will repeat.

A fix will be to place increment of AIH after you alter AIHS. This is actually the most common cause of errors, you first apply unchanged value, then change it, instead of first changing, then applying.

OTHER TIPS

In the following if statement:

if(pdl_R.y==stage.stageHeight || pdl_R.y==stage.stageHeight-pdl_R.height)
{
    AIHS*=-1;
}

Using some example figures for the paddle height (30) and the stage height (600), you're asking:

if(paddle.y == 600 || paddle.y == 570)
{
  ReversePaddleDirection
}

This would explain the paddle becoming stuck at the bottom as it would forever be bouncing between 570 and 600, reversing as soon as it reaches one or the other.

If this isn't the case we could use some more information (ie the actual stage height and paddle height) to debug further.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top