2013-07-30 59 views
0

在我的乒乓球比賽中,我有一個球和兩個槳。我想這樣,當ball.ballRect.x < 5truescore.greenScore增量就像這樣:score.greenScore++;XNA - 改變矩形的位置

而且行之有效,但我也希望它使球移動到屏幕的中央。因此,在Game1.cs

我這樣做:

public void ScoreAdder() 
    { 
     if (ball.ballRect.X < 5) 
     { 
      score.blueScore++; 
      ball.ballRect = new Rectangle((int)400, (int)250, ball.ballTexture.Width, ball.ballTexture.Height); 
     } 

    } 

這又回到了中心,並增加了比分,但現在也不會聽的碰撞。

在我Ball.cs我只繪製矩形,如:

spriteBatch.Draw(ballTexture, ballRect, Color.White);

因爲當我使用Vector2位置,球甚至不會出現在屏幕上。

+1

你的碰撞代碼是什麼? – Cyral

+1

聽起來像你需要更新你的ballRect變量來反映你的球的新位置。 – jgallant

+0

當你重生時,你是否嘗試過設置Position.X rect.X,並將Position.Y改爲rect.Y? – Cyral

回答

1

您是否重置了Position當您將球重新放到中央?

你可以利用這個屬性,並且Position指向Rectangle,反之亦然。

public Vector2 BallPosition 
{ 
    get 
    { 
     return ballPosition; 
    } 
    set 
    { 
     ballRectangle.X = value.X; 
     ballRectangle.Y = value.Y; 
     ballPosition = value; 
    } 
} 
private Vector2 ballPosition 

我不知道你如何處理衝突和一切,但只要你設置將設置矩形的位置,你也可以嘗試相反,在這裏設置矩形,它會與同步位置。

1

我不知道你是如何封裝球的邏輯,但這裏是我可能試圖做到這一點。使用這樣的類可以保證球的所有內部邏輯都位於一個位置,以便可以根據位置和界限預測生成的繪圖矩形。不再使用vector2消失的球!

public class Ball 
{ 
private Vector2 _position; 
private Vector2 _velocity; 
private Point _bounds; 

public Vector2 Position { get { return _position; } set { _position = value; } } 
public Vector2 Velocity { get { return _velocity; } set { _velocity = value; } } 
public int LeftSide { get { return (int)_position.X - (_bounds.X/2); } } 
public int RightSide { get { return (int)_position.X + (_bounds.X/2); } } 
public Rectangle DrawDestination 
{ 
    get 
    { 
     return new Rectangle((int)_position.X, (int)_position.Y, _bounds.X, _bounds.Y); 
    } 
} 

public Ball(Texture2D ballTexture) 
{ 
    _position = Vector2.Zero; 
    _velocity = Vector2.Zero; 
    _bounds = new Pointer(ballTexture.Width, ballTexture.Height); 
} 

public void MoveToCenter() 
{ 
    _position.X = 400.0f; 
    _position.Y = 250.0f; 
} 

public void Update(GameTime gameTime) 
{ 
    _position += _velocity; 
} 
} 

然後在你更新/繪製代碼:

class Game 
{ 
void Update(GameTime gameTime) 
{ 
    // ... 

    ball.Update(gameTime); 

    if(ball.LeftSide < LEFT_BOUNDS) 
    { 
     score.blueScore++;  
     ball.MoveToCenter(); 
    } 
    if(Ball.RightSide > RIGHT_BOUNDS) 
    { 
     score.greenScore++; 
     ball.MoveToCenter(); 
    } 

    // ... 
} 

void Draw(GameTime gameTime) 
{ 
    // ... 

    _spriteBatch.Draw(ballTexture, ball.DrawDestination, Color.White); 

    // ... 
} 
} 

記住也由過去幀時間調節球的速度。