### XNA–A Simple Spring Camera in 2D

Cameras are cool, so lets keep at it and try a spring camera, i.e. one that follows you around.

The initial aspect of the camera and how to use it is on the previous post on cameras, so I ll let you go and have a look there.

The spring camera is very similar to a simple camera, but with Hooke’s Law applied. Hooke’s Law states that the extension of a helical spring is directly proportional to the weight applied, provided the elastic limit of the spring is not exceeded. I read this a few times and couldnt figure how to turn this into code , so I went to Khan Academy and found this video, where the formula **F = –k x** is explained.

If we use the formula as is, then the spring would be “springing” forever, so when calculating the force we will use some damping. So the new update method in Camera.cs now looks like this

1: public void Update(float elapsedSeconds, float rotation, Vector2 desiredPosition, float zoom)

` 2: {`

` 3: var delta = _position - desiredPosition;`

` 4: var force = -SpringStiffness * delta - Damping * _velocity;`

` 5:`

` 6: var acceleration = force / Mass;`

` 7: _velocity += acceleration * elapsedSeconds;`

` 8: _position += _velocity * elapsedSeconds;`

` 9:`

` 10: Transform = Matrix.CreateTranslation(-_position.X, -_position.Y, 0) *`

` 11: Matrix.CreateRotationZ(rotation) *`

` 12: Matrix.CreateScale(zoom, zoom, 1)*`

` 13: Matrix.CreateTranslation(_halfScreenSize.X, _halfScreenSize.Y, 0);`

` 14: }`

The line

var force = -SpringStiffness * delta – Damping * _velocity;

Is respecting the formula F= –kx, where k is the SpringStiffness and x is the delta(in orange). The second part of this assignment(in green) is applying some damping proportional to the velocity.

Once we have the result of calculating the force, we use the force vector to calculate the acceleration that, in turn that value is used to calculate the velocity and position.

Finally, once we have the position, the matrix transformation is calculated in the same way we calculated this for the simple camera (in previous post).

You can get a complete working sample here.

Filed under: Uncategorized | Leave a Comment

Tags: acceleration force mass, programming

## No Responses Yet to “XNA–A Simple Spring Camera in 2D”