Imagine a segmented creature such as a centipede. With control of the head segment, the body segments are attached to the previous body segment by a point.
As the head moves (in the 8 cardinal/inter-cardinal directions for now) a point moves in relation to its rotation.
public static Vector2 RotatePoint(Vector2 pointToRotate, Vector2 centerOfRotation, float angleOfRotation)
{
Matrix rotationMatrix = Matrix.CreateRotationZ(angleOfRotation);
return Vector2.Transform(pointToRotate - centerOfRotation, rotationMatrix);
}
Was going to post a diagram here but you know…
center(2) point(2) center(1) point(1)
point(1)
point(2) ^ |
/ \ |
| |
center(2) center(1) \ /
V
I have thought of using a rectangle property/field for the base sprite,
private Rectangle bounds = new Rectangle(-16, 16, 32, 32);
and checking that a predefined point within the body segment remains within the head sprite’s bounds.
Though I am currently doing:
private static void handleInput(GameTime gameTime)
{
Vector2 moveAngle = Vector2.Zero;
moveAngle += handleKeyboardMovement(Keyboard.GetState()); // basic movement, combined to produce 8 angles
// of movement
if (moveAngle != Vector2.Zero)
{
moveAngle.Normalize();
baseAngle = moveAngle;
}
BaseSprite.RotateTo(baseAngle);
BaseSprite.LeftAnchor = RotatePoint(BaseSprite.LeftAnchor,
BaseSprite.RelativeCenter, BaseSprite.Rotation); // call RotatePoint method
BaseSprite.LeftRect = new Rectangle((int)BaseSprite.LeftAnchor.X - 1,
(int)BaseSprite.LeftAnchor.Y - 1, 2, 2);
// All segments use a field/property that is a point which is suppose to rotate around the center
// point of the sprite (left point is (-16,0) right is (16,0) initially
// I then create a rectangle derived from that point to make use of the .Intersets method of the
// Rectangle class
BodySegmentOne.RightRect = BaseSprite.LeftRect; // make sure segments are connected?
BaseSprite.Velocity = moveAngle * wormSpeed;
//BodySegmentOne.RightAnchor = BaseSprite.LeftAnchor;
if (BodySegmentOne.RightRect.Intersects(BaseSprite.LeftRect)) // as long as there two rects occupy the
{ // same space move segment with head
BodySegmentOne.Velocity = BaseSprite.Velocity;
}
}
As it stands now, the segment moves with head but in a parallel fashion. I would like to get a more nuanced movement of the segment as it is being dragged by the head.
I understand that the coding of such movement will be much more involved than what I have here. Some hints or directions as to how I should look at this problem would be greatly appreciated.
I will describe what you need to do using a physics engine like Farseer but the same holds if you want to write your own physics engine.
For example – assuming that the outer shell of each link is a circle, here’s how to create two links and join them together.
Now applying a force on any of the bodies or collisions on the shapes will drag the second joint around – just like you want.
This is all just stick physics – so you could implement your own if you REALLY wanted to. 😉