-2
\$\begingroup\$

The collision is not working correctly! The collision is in the "open-word" and not when it collides! Here my code:

Platform code(static):

body = BodyFactory.CreateRectangle(world, (float)ConvertUnits.ToSimUnits(textureplattform.Width), (float)ConvertUnits.ToSimUnits(textureplattform.Height),1f); body.BodyType = BodyType.Static; body.Position = new Vector2(ConvertUnits.ToSimUnits(Position.X) + textureplattform.Width/2,ConvertUnits.ToSimUnits(Position.Y) + textureplattform.Height/2); 

Player code(dynamic):

body = BodyFactory.CreateRectangle(world,(float)ConvertUnits.ToSimUnits(playertexture.Width), (float)ConvertUnits.ToSimUnits(playertexture.Height), 1f); body.BodyType = BodyType.Dynamic; body.Position = new Vector2(ConvertUnits.ToSimUnits(position.X), ConvertUnits.ToSimUnits(position.Y)); body.Mass = 1f; 

Player draw:

public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(playertexture, ConvertUnits.ToDisplayUnits(body.Position),null,Color.White, ConvertUnits.ToDisplayUnits(body.Rotation), new Vector2(playertexture.Width / 2, playertexture.Height / 2), 1f,SpriteEffects.None, 0f); } 

Platform draw:

public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(textureplattform, ConvertUnits.ToDisplayUnits(body.Position), colorplat); } 
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

I think the problem is in you drawing code, not in the collision code. So the objects are colliding correctly, but you're drawing them in the wrong place.

Looking at your draw code I notice two anomalies:

  1. You forgot to draw with the origin set to the center of the sprite when drawing the platform. This is mandatory because Body.Position refers to the center of mass of the object, which on a rectangular sprite, is at the center. You already seem to be doing this for the player so I won't bother repeating how it's done.

  2. When drawing the player, or any other sprite for that matter, you shouldn't convert the rotation to display units. Angles don't change no matter what the scale is. You only need to convert positions and widths/heights.

To make things easier, I would recommend writing an helper method for drawing physics bodies. Then reuse this method in every class that needs to draw a body:

public static void DrawBody(SpriteBatch spriteBatch, Texture2D texture, Body body, Color color) { spriteBatch.Draw(texture, ConvertUnits.ToDisplayUnits(body.Position), null, color, body.Rotation, new Vector2(texture.Width / 2f, texture.Height / 2f), 1f, SpriteEffects.None, 0f); } 

PS: Where you're setting body.Position for the platform, you should apply ConvertUnits.ToSimUnits to width/2 and height/2 too, if you want it to behave as you expect.

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.