2017-03-26 10 views
0

私はスプライト、Playerを持っています。 _position_direction_velocityVector2のあるXNA/Monogame:プラットジャンプ物理学と衝突問題

_position += (_direction * _velocity) * (float)gameTime.ElapsedGameTime.TotalSeconds;

:私はPlayerの位置次のように更新します。

私は単純なコライダー(BoxCollider)を用意しています。コイダーの位置と大きさを指定すると、矩形(BoundingBox)が生成されます。 Initialize()

、私は新しいList<BoxCollider>を作成し、レベルのためのコライダーでそれを埋めます。 Update()

、私は衝突をチェックするPlayerにリストを渡します。

衝突チェック方法:今

public void CheckPlatformCollision(List<BoxCollider> colliders, GameTime gameTime) 
{ 
    var nextPosition = _position + (_direction * _velocity) * (float)gameTime.ElapsedGameTime.TotalSeconds; 
    Rectangle playerCollider = new Rectangle((int)nextPosition.X, (int)nextPosition.Y, BoundingBox.Width, BoundingBox.Height); 
    foreach(BoxCollider collider in colliders) 
    { 
     if(playerCollider.Intersects(collider.BoundingBox)) 
     { 
      nextPosition = _position; 
     } 
    } 
    Position = nextPosition; 
} 

、私は重力を実装しようとしたあらゆる方法に失敗しました。 Playerが高すぎるから削除された場合、nextPositionが離れすぎてPlayerからなり、それは空中で立ち往生したまま。

私はまた、同様に水平方向の衝突の問題を抱えている問題は、類似している:あまりにも早く停止しPlayer、間にスペースを残します。時には、私はPlayerをコライダーの側に付いています。

私が知りたいのです:

がどのように適切に_position_direction、および_velocityでジャンプ重力&を実装していますか?水平と垂直の両方で適切に衝突を処理するにはどうすればよいですか?重力のために

+0

これはおそらくあなたを助けるでしょう:http://gamedev.stackexchange.com/questions/104954/2d-collision-detection-xna-c – vyrp

答えて

1

、あなたが_positionを更新する直前にこれを追加します。

_velocity += gravity * (float)gameTime.ElapsedGameTime.TotalSeconds; 

gravitynew Vector2(0, 10)のようなものであるところ。ジャンプするための


、あなたはプレイヤーがジャンプボタン押したときの速度の垂直成分を設定する必要があります。

if (jumpPressed && jumpAvailable) 
{ 
    _velocity.Y = -10; // Numbers are example. You need to adjust this 
    jumpAvailable = false; 
} 

をそして、あなたはプレイヤーが床に触れたときjumpAvailableをリセットする必要があります。


衝突は非常に複雑です。しかし、あなたがインターネット上で "XNA implement collision"を探すなら、多くの答えを見つけるでしょう。

多くの方法があります。そのうちの1人は、あなたがコードで行ったように、彼を移動させない代わりに、プレーヤーをboxcolliderの境界に押し戻しています。コードは次のようになります。ヘルパーメソッドは次のように実施することができる

if (IntersectsFromTop(playerCollider, collider.BoundingBox)) 
{ 
    _position.Y = collider.BoundingBox.Y - BoundingBox.Height; 
} 
else if (IntersectsFromRight(playerCollider, collider.BoundingBox)) 
{ 
    _position.X = collider.BoundingBox.X + collider.BoundingBox.Width; 
} 
// And so on... 

private static bool IntersectsFromTop(Rectange player, Rectangle target) 
{ 
    var intersection = Rectangle.Intersect(player, target); 
    return player.Intersects(target) && intersection.Y == target.Y && intersection.Width >= intersection.Height; 
} 

private static bool IntersectsFromRight(Rectange player, Rectangle target) 
{ 
    var intersection = Rectangle.Intersect(player, target); 
    return player.Intersects(target) && intersection.X + intersection.Width == target.X + target.Width && intersection.Width <= intersection.Height; 
} 
// And so on... 

そのコードの後ろにrationnaleは、ピクチャで説明することができる。その画像に

Top collision and left collision

widthheightは紫色の交差点に対応します。