Quaternion rotation in XNA - c#

Am I doing the following right?
Well obviously not cause otherwise I wont be posting a question here, but I'm trying to do a Quaternion rotation of a model around another model.
Lets say I have a box model that has a vector3 position and a float rotation angle.
I also have a frustum shaped model that is pointing towards the box model, with its position lets say 50 units from the box model. The frustum also has a vector3 position and a Quaternion rotation.
In scenario 1, the box and frustum are "unrotated". This is all fine and well.
In scenario 2, I rotate the box only and I want the frustum to rotate with it (kinda like a chase camera) with the frustum always pointing directly at the box and at the same distance from the box as in the unrotated distance. Obviously if I just rotate the model and the frustum by using Matrix.CreateRotationY() for both the box and the frustum, the frustum is slightly offset to the side.
So I thought a Quaternion rotation of the frustum around the box would be best?
To this end I have tried the following, with no luck. It draws my models on the screen, but it also draws what looks like a giant box to the screen and no matter how far away I move the camera the box is always in the way
For the purpose of testing, I have 3 boxes and their 3 associated frustums
In my Game1 class I initialize the box[0] with positions and rotations
boxObject[0].Position = new Vector3(10, 10, 10);
boxObject[1].Position = new Vector3(10, 10, 10);
boxObject[2].Position = new Vector3(10, 10, 10);
boxObject[0].Rotation = 0.0f;
boxObject[1].Rotation = 45.0f;
boxObject[2].Rotation = -45.0f;
So all 3 boxes drawn at the same position but at different angles.
Then to do the frustums, I initiate their position:
float f = 50.0f;
frustumObject[0].Position = new Vector3(boxObject[0].Position.X,
boxObject[0].Position.Y, boxObject[0].Position.Z + f);
frustumObject[1].Position = new Vector3(boxObject[1].Position.X,
boxObject[1].Position.Y, boxObject[1].Position.Z + f);
frustumObject[2].Position = new Vector3(boxObject[2].Position.X,
boxObject[2].Position.Y, boxObject[2].Position.Z + f);
And then try and rotate around their associated box model:
frustumObject[0].ModelRotation = new Quaternion(boxObject[0].Position.X,
boxObject[0].Position.Y, boxObject[0].Position.Z + f, 0);
frustumObject[0].ModelRotation = new Quaternion(boxObject[0].Position.X,
boxObject[0].Position.Y, boxObject[0].Position.Z + f, 45);
frustumObject[0].ModelRotation = new Quaternion(boxObject[0].Position.X,
boxObject[0].Position.Y, boxObject[0].Position.Z + f, -45);
And finally, to draw the models, I Draw() them in my GameModel class which also has:
public Model CameraModel { get; set; }
public Vector3 Position { get; set; }
public float Rotation { get; set; }
public Quaternion ModelRotation { get; set; }
public void Draw(Matrix view, Matrix projection)
{
transforms = new Matrix[CameraModel.Bones.Count];
CameraModel.CopyAbsoluteBoneTransformsTo(transforms);
// Draw the model
foreach (ModelMesh myMesh in CameraModel.Meshes)
{
foreach (BasicEffect myEffect in myMesh.Effects)
{
// IS THIS CORRECT?????
myEffect.World = transforms[myMesh.ParentBone.Index] *
Matrix.CreateRotationY(Rotation) * Matrix.CreateFromQuaternion(ModelRotation) * Matrix.CreateTranslation(Position);
myEffect.View = view;
myEffect.Projection = projection;
myEffect.EnableDefaultLighting();
myEffect.SpecularColor = new Vector3(0.25f);
myEffect.SpecularPower = 16;
}
myMesh.Draw();
}
}
Can anyone spot where I am going wrong? Is it because I am doing 2 types of rotations n the Draw()?
myEffect.World = transforms[myMesh.ParentBone.Index] *
Matrix.CreateRotationY(Rotation) * Matrix.CreateFromQuaternion(ModelRotation) * Matrix.CreateTranslation(Position);

From a quick glance, it would be best to create your Quaternions using a static create method such as Quaternion.CreateFromAxisAngle(Vector3. UnitY, rotation). The values of X,Y,Z and W of a Quaternion do not relate to position in any way. The handy static methods take care of the tricky math.
In your situation it appears as though you want to keep the frustum pointing at the same side of the box as the box rotates, therefore rotating the frustum about the box. This requires a slightly different approach to the translation done in your draw method.
In order to rotate an object about another, you first need to translate the object so that the centre of the desired rotation is at the origin. Then rotate the object and translate it back by the same amount as the first step.
So in you situation, something like this should do it (untested example code to follow);
// Construct the objects
boxObject.Position = new Vector3(10, 10, 10);
boxObject.Rotation = 45.0f;
frustumObject.Position = new Vector3(0, 0, 50f); // Note: this will be relative to the box (makes the math a bit simpler)
frustumObject.TargetPosition = boxObject.Position;
frustumObject.ModelRotation = Quaternion.CreateFromAxisAngle(Vector3. UnitY, boxObject.Rotation); // Note: this rotation angle may need to be in radians.
// Box Draw()
// Draw the box at its position, rotated about its centre.
myEffect.World = transforms[myMesh.ParentBone.Index] * Matrix.CreateTranslation(Position) * Matrix.CreateRotationY(Rotation);
// Frustum Draw()
// Draw the frustum facing the box and rotated about the boxes centre.
myEffect.World = transforms[myMesh.ParentBone.Index] * Matrix.CreateTranslation(Position) * Matrix.CreateFromQuaternion(ModelRotation) * Matrix.CreateTranslation(TargetPosition);
Assumptions:
The box rotates about its own centre
The frustum stays facing the box and rotates around the boxes centre
Hope this helps.

Related

How to get color of the pixel I clicked on in Unity? Is there a GetPixel alternative that works with floats?

I'm using a Texture2D to display a map, and I need to get the color of the pixel I clicked on. I used Input.mousePosition to get the float coordinates, but using GetPixel to get the color requires the coordinates to be integers.
I am having trouble with getting GetPixel to find the coordinate that I clicked on.
When using floats and clicking on say, the rightmost side of the texture, I get a number like 27.xxx, but when I cast it to an integer, it displays a coordinate 27 pixels from the leftmost side of the texture. The way floats represent pixels confuses me a great deal, maybe clarifying that would help.
public class ProvinceSelectScript : MonoBehaviour {
public Material SpriteMain;
public Color SelectedCol;
public Color NewlySelectedCol;
public Texture2D WorldColMap;
Vector2 screenPosition;
Vector2 worldPosition;
void Start()
{
WorldColMap = (Texture2D)SpriteMain.GetTexture("_MainTexture");
NewlySelectedCol = Color.blue;
}
private void OnMouseDown()
{
screenPosition = new Vector2(Input.mousePosition.x,Input.mousePosition.y);
worldPosition = Camera.main.ScreenToWorldPoint(screenPosition);
SelectedCol = WorldColMap.GetPixel(((int)(worldPosition.x)+(WorldColMap.width/2)) , (int)((worldPosition.y)+(WorldColMap.height / 2)));
SpriteMain.SetColor("_SelectedProvince", SelectedCol);
SpriteMain.SetColor("_NewlySelectedProvince", NewlySelectedCol);
}
}
The worldPosition in the question isn't calculated in a way that's useful if you're using a perspective camera or if your camera is pointed any direction but directly forward.
To find the world position of the click, the best way to go about that is to use Camera.ScreenPointToRay to calculate the position of the click when intersecting the plane made by the position of the sprite and its local forward.
Either way, a world position does not mean anything to the sprite, which could be positioned anywhere in world space. You should rather use transform.InverseTransformPoint to calculate the local position you're clicking on. At that point, you can then use the spriterenderer's bounds to convert to normalized form (0-1 originating fromt he bottom-left instead of world unit lengths originating from the center).
But, once you have the local sprite position of the click expressed in normalized form, you can try to use GetPixelBilinear to get the color at the UV of (x,y) of the click. If the sprite is super simple, this MAY work. If it is animated or nine-sliced, or anything else it probably won't, and you'll have to reverse-engineer what UV the mouse is actually hovering over.
Camera mainCam;
SpriteRenderer sr;
void Start()
{
WorldColMap = (Texture2D)SpriteMain.GetTexture("_MainTexture");
NewlySelectedCol = Color.blue;
mainCam = Camera.main; // cache for faster access
sr = GetComponent<SpriteRenderer>(); // cache for faster access;
}
private void OnMouseDown()
{
Plane spritePlane = new Plane(transform.position, transform.forward);
Ray pointerRay = Camera.main.ScreenPointToRay(Input.mousePosition);
if (spritePlane.Raycast(pointerRay, out distance))
{
Vector3 worldPositionClick = pointerRay.GetPoint(distance);
Vector3 localSpriteClick = transform.InverseTransformPoint(worldPositionClick);
// convert [(-extents,-extents),(extents,extents)] to [(0,0),(1,1)]
Vector3 localSpriteExtents = sr.sprite.bounds.extents;
localSpriteClick = localSpriteClick + localSpriteExtents ;
localSpriteClick.x /= localSpriteExtents.x * 2;
localSpriteClick.y /= localSpriteExtents.y * 2;
// You clicked on localSpriteClick, on a very simple sprite (where no uv magic is happening) this might work:
SelectedCol = WorldColMap.GetPixelBilinear(localSpriteClick.x, localSpriteClick.y);
SpriteMain.SetColor("_SelectedProvince", SelectedCol);
}

Need help on monogame screen resolution and intersection

Currently in my game i want trying to move my object towards both x axis and y axis.As I also wanted to put it into center ,I have put a camera.Here is my Camera code-
public class Camera
{
public Matrix transform;
public Viewport view;
public Vector2 origin;
Vector2 baseScreenSize = new Vector2(1136, 720);
float horScaling ;
float verScaling ;
Vector3 screenScalingFactor ;
public Camera(Viewport newView)
{
view = newView;
horScaling = view.Width / baseScreenSize.X;
verScaling = view.Height / baseScreenSize.Y;
screenScalingFactor = new Vector3(horScaling, verScaling, 1);
}
public void update(GameTime gt, ball pl)
{
origin = new Vector2(pl.Position.X + (pl.ballRectangle.Width / 2) - 400, 0);
transform = Matrix.CreateScale(1,1,0) *
Matrix.CreateTranslation(new Vector3(-origin.X, -origin.Y, 0));
}
}
and in Game1.cs file as usual in begin statement i am putting this-
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, cm.transform*globalTransformation);
ba.Draw(spriteBatch, Color.White);
spriteBatch.End();
Here ba is the object of ball,its just have moving x and y functionalities.
In a separate begin,end statement ,I am drawing rest all of the objects-
spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, null, globalTransformation);
spriteBatch.Draw(mainMenu, new Vector2(0, 0), Color.White);
spriteBatch.Draw(mainMenu1, new Vector2(450, 100), Color.White);
spriteBatch.End();
Here Have applied globaltransformation to acheive independent screen resolution(similar codes like in Camera.cs).
Rest of the objects are working as expected,But intersections of camera object and rest of the objects is not working as expected.
I guess this is due to resolution independency is not applied to Camera object(I am not sure).I have tried lot of codes after searching internet,but none of them is working as expected.
In a simple words-I want to clone this game-
https://play.google.com/store/apps/details?id=com.BitDimensions.BlockyJump
If you see main player is moving along x and y axis,but due to camera its in constant position,but the obstacles are not in camera,How to acheive the intersection between obejct which is in camera draw and objects which are not in camera in this case
Request all to help,I am stuck here from long time...
Never thought this will be this much of easy...Searched all over internet,in
most of the codes they were saying we need to inverse the camera transform.
But this is not the case.As from beginning I was saying my problem is intersection between camera object and non camera object,here is the answer-
First of all we need to find the positions of camera object to form a world space rectangle
Vector2 hj = Vector2.Transform(ba.Position, cm.transform);
Rectangle leftRectangleT1 =
new Rectangle((int)hj.X, (int)hj.Y, ba.tex.Width, ba.tex.Height);
Here ba is the camera object,we need to transform it to camera transform like above codes.
To get transform of ba in case pixel intersection,here is the codes-
Matrix ballTransform = Matrix.CreateTranslation(new Vector3(hj.X, hj.Y, 0.0f));
Thats it you have ball rectangle which is camera object to intersect with real world objects(non camera objects)
I don't understand your question per say, but from what I gathered, you want the camera to follow the target's position, and you also want independent screen resolutions?
Well, for the independent screen resolution, simply create a screen resolution handler that renders the scene to a RenderTarget2D as defined by your sizes. Then draw that to the screen.
For the camera movement. Try adjusting the camera's position to follow the target's position with an offset and slerp interpolation to prevent stuttering and smooth action.
void Update(float gameTime) {
Vector3 camTransform = Camera.Position + cameraTarget;
Vector3 newCameraPosition = Vector3.Slerp(cameraPosition, camTransform, 0.2f);
Camera.Position = newCameraPosition;
}
For your intersection problem try something along this
private bool intersects(rectangle1, rectangle2) {
return rectangle1.x >= rectangle2.x &&
rectangle1.y >= rectangle2.y &&
rectangle1.y <= rectangle2.y + rectangle2.h &&
rectangle1.x <= rectangle2.x + rectangle2.w;
}
private void checkIntersections(gameObjects[]) {
foreach (var obj in gameobjects) {
if (intersects(obj.rectangle, camera.rectangle){
handleIntersections(camera, obj);
}
}
}

Issues with transform.Rotate in Unity

I have been working on programming a graph in Unity that rotates based on head movement. I have been having multiple issues with the rotation aspect of it.
A sample of the Autowalk class, which I am using to find the angle that the graph needs to rotate based on where the user is facing:
public class AutoWalk : MonoBehaviour {
//VR head
private Transform vrHead;
//angular displacement from normal
public float xAng, yAng, zAng;
//previous values
public float xOrig, yOrig, zOrig;
// Use this for initialization
void Start () {
//Find the VR head
vrHead = Camera.main.transform;
//finding the initial direction
Vector3 orig = vrHead.TransformDirection(Vector3.forward);
xOrig = orig.x;
yOrig = orig.y;
zOrig = orig.z;
}
// Update is called once per frame
void Update () {
//find the forward direction
Vector3 forward = vrHead.TransformDirection(Vector3.forward);
float xForward = forward.x;
float yForward = forward.y;
float zForward = forward.z;
//find the angle between the initial and current direction
xAng = Vector3.Angle(new Vector3(xOrig, 0, 0), new Vector3(xForward, 0, 0));
yAng = Vector3.Angle(new Vector3(0, yOrig, 0), new Vector3(0, yForward, 0));
zAng = Vector3.Angle(new Vector3(0, 0, zOrig), new Vector3(0, 0, zForward));
//set new original angle
xOrig = xAng;
yOrig = yAng;
zOrig = zAng;
}
From there I go to the ReadingPoints class, which contains all of the points on the graphs (spheres) and axes (stretched out cubes):
public class ReadingPoints : MonoBehaviour {
// Update is called once per frame
void Update () {
float xAngl = GameObject.Find("GvrMain").GetComponent<AutoWalk>().xAng;
float yAngl = GameObject.Find("GvrMain").GetComponent<AutoWalk>().yAng;
float zAngl = GameObject.Find("GvrMain").GetComponent<AutoWalk>().zAng;
if ((xAngl != prevXAngl) || (yAngl!=prevYAngl) || (zAngl!=prevZAngl))
{
//rotate depending on the angle from normal
foreach (GameObject o in allObjects)
{
o.transform.Rotate(new Vector3(xAngl, yAngl, zAngl), Space.World);
prevXAngl = xAngl;
prevYAngl = yAngl;
prevZAngl = zAngl;
}
}
allObjects, as the name implies, contains the points and the axes.
Anyway, the first issue that is upon running the program is that the graph appears to be torn apart.
How the graph is supposed to look (this is what it looks like when o.transform.Rotate(...) is commented out)
Here is how it actually looks :( Also, the graph does not rotate when I move, and I have no idea why (I thought I might be using the Rotate function improperly but perhaps I also didn't find the correct angles?). Any ideas of what went wrong are much appreciated, thank you!
First of all I think you should start using Quaternions (https://docs.unity3d.com/ScriptReference/Quaternion.html)
Secondly; while you rotate a object with a Camera attached its line of view will change and eventually the object(Graph) will be out of view. If you want as much of the full graph as possible to remain in view of camera as long as possible. You should give the Quaternion of the graph the opposite rotation of that applied to your Camera or the object it is attached to.
Make sure your all elements of your graph are children of a central gameobject in your graph, and only manipulate that point.

How do I rotate meshes around their local axes in XNA?

I have an object in my game that has a few meshes and when I try to rotate either of the meshes either way, it only rotates it around world axis, and not its local axis. I have a rotation = Matrix.Identity in a class constructor. Every mesh has this class attached to it. Then this class also contains methods:
...
public Matrix Transform{ get; set; }
public void Rotate(Vector3 newRot)
{
rotation = Matrix.Identity;
rotation *= Matrix.CreateFromAxisAngle(rotation.Up, MathHelper.ToRadians(newRot.X));
rotation *= Matrix.CreateFromAxisAngle(rotation.Right, MathHelper.ToRadians(newRot.Y));
rotation *= Matrix.CreateFromAxisAngle(rotation.Forward, MathHelper.ToRadians(newRot.Z));
CreateMatrix();
}
private void CreateMatrix()
{
Transform = Matrix.CreateScale(scale) * rotation * Matrix.CreateTranslation(Position);
}
...
And now the Draw() method:
foreach (MeshProperties mesh in model.meshes)
{
foreach (BasicEffect effect in mesh.Mesh.Effects)//Where Mesh is a ModelMesh that this class contains information about
{
effect.View = cam.view;
effect.Projection = cam.projection;
effect.World = mesh.Transform;
effect.EnableDefaultLighting();
}
mesh.Mesh.Draw();
}
EDIT:
I am afraid either I screwed somewhere up, or your tehnique does not work, this is what I did. Whenever I move the whole object(Parent), I set its Vector3 Position; to that new value. I also set every MeshProperties Vector3 Position; to that value. And then inside CreateMatrix() of MeshProperties I did like so:
...
Transform = RotationMatrix * Matrix.CreateScale(x, y, z) * RotationMatrix * Matrix.CreateTranslation(Position) * Matrix.CreateTranslation(Parent.Position);
...
Where:
public void Rotate(Vector3 newRot)
{
Rotation = newRot;
RotationMatrix = Matrix.CreateFromAxisAngle(Transform.Up, MathHelper.ToRadians(Rotation.X)) *
Matrix.CreateFromAxisAngle(Transform.Forward, MathHelper.ToRadians(Rotation.Z)) *
Matrix.CreateFromAxisAngle(Transform.Right, MathHelper.ToRadians(Rotation.Y));
}
And Rotation is Vector3.
RotationMatrix and Transform are both set to Matrix.Identity in the constructor.
The problem is if I try to rotate around for example Y axis, he should rotate in a circle while "standing still". But he moves around while rotating.
I'm not entirely certain this is what you want. I'm assuming here you have an object, with some meshes and positions offset from the position and orientation of the main object position and you want to rotate the child object around its local axis relative to the parent.
Matrix.CreateTranslation(-Parent.Position) * //Move mesh back...
Matric.CreateTranslation(-Mesh.PositionOffset) * //...to object space
Matrix.CreateFromAxisAngle(Mesh.LocalAxis, AngleToRotateBy) * //Now rotate around your axis
Matrix.CreateTranslation(Mesh.PositionOffset) * //Move the mesh...
Matrix.CreateTranslation(Parent.Position); //...back to world space
Of course you usually store a transform matrix which transforms a mesh from object space to world space in one step, and you'd also store the inverse. You also store the mesh in object coordinates all the time and only move it into world coordinate for rendering. This would simplify things a little:
Matrix.CreateFromAxisAngle(Mesh.LocalAxis, AngleToRotateBy) * //We're already in object space, so just rotate
ObjectToWorldTransform *
Matrix.CreateTranslation(Parent.Position);
I think you could simply set Mesh.Transform in your example to this and be all set.
I hope this is what you were looking for!
The problem was that, when I was exporting model as .FBX the pivot point wasnt in model centre. Thus making the model move while rotating.

Having the Background or Camera "Scroll" based on charcter position

I'm working on an RPG game that has a Top-Down view. I want to load a picture into the background which is what the character is walking on, but so far I haven't figured out how to correctly have the background redraw so that it's "scrolling". Most of the examples I find are auto scrolling.
I want the camera to remained centered at the character until you the background image reaches its boundaries, then the character will move without the image re-drawing in another position.
Your question is a bit unclear, but I think I get the gist of it. Let's look at your requirements.
You have an overhead camera that's looking directly down onto a two-dimensional plane. We can represent this as a simple {x, y} coordinate pair, corresponding to the point on the plane at which the camera is looking.
The camera can track the movement of some object, probably the player, but more generally anything within the game world.
The camera must remain within the finite bounds of the game world.
Which is simple enough to implement. In broad terms, somewhere inside your Update() method you need to carry out steps to fulfill each of those requirements:
if (cameraTarget != null)
{
camera.Position = cameraTarget.Position;
ClampCameraToWorldBounds();
}
In other words: if we have a target object, lock our position to its position; but make sure that we don't go out of bounds.
ClampCameraToBounds() is also simple to implement. Assuming that you have some object, world, which contains a Bounds property that represents the world's extent in pixels:
private void ClampCameraToWorldBounds()
{
var screenWidth = graphicsDevice.PresentationParameters.BackBufferWidth;
var screenHeight = graphicsDevice.PresentationParameters.BackBufferHeight;
var minimumX = (screenWidth / 2);
var minimumY = (screnHeight / 2);
var maximumX = world.Bounds.Width - (screenWidth / 2);
var maximumY = world.Bounds.Height - (screenHeight / 2);
var maximumPos = new Vector2(maximumX, maximumY);
camera.Position = Vector2.Clamp(camera.Position, minimumPos, maximumPos);
}
This makes sure that the camera is never closer than half of a screen to the edge of the world. Why half a screen? Because we've defined the camera's {x, y} as the point that the camera is looking at, which means that it should always be centered on the screen.
This should give you a camera with the behavior that you specified in your question. From here, it's just a matter of implementing your terrain renderer such that your background is drawn relative to the {x, y} coordinate specified by the camera object.
Given an object's position in game-world coordinates, we can translate that position into camera space:
var worldPosition = new Vector2(x, y);
var cameraSpace = camera.Position - world.Postion;
And then from camera space into screen space:
var screenSpaceX = (screenWidth / 2) - cameraSpace.X;
var screenSpaceY = (screenHeight / 2) - cameraSpace.Y;
You can then use an object's screen space coordinates to render it.
Your can represent the position in a simple Vector2 and move it towards any entity.
public Vector2 cameraPosition;
When you load your level, you will need to set the camera position to your player (Or the object it should be at)
You will need a matrix and some other stuff, As seen in the code below. It is explained in the comments. Doing it this way will prevent you from having to add cameraPosition to everything you draw.
//This will move our camera
ScrollCamera(spriteBatch.GraphicsDevice.Viewport);
//We now must get the center of the screen
Vector2 Origin = new Vector2(spriteBatch.GraphicsDevice.Viewport.Width / 2.0f, spriteBatch.GraphicsDevice.Viewport.Height / 2.0f);
//Now the matrix, It will hold the position, and Rotation/Zoom for advanced features
Matrix cameraTransform = Matrix.CreateTranslation(new Vector3(-cameraPosition, 0.0f)) *
Matrix.CreateTranslation(new Vector3(-Origin, 0.0f)) *
Matrix.CreateRotationZ(rot) * //Add Rotation
Matrix.CreateScale(zoom, zoom, 1) * //Add Zoom
Matrix.CreateTranslation(new Vector3(Origin, 0.0f)); //Add Origin
//Now we can start to draw with our camera, using the Matrix overload
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default,
RasterizerState.CullCounterClockwise, null, cameraTransform);
DrawTiles(spriteBatch); //Or whatever method you have for drawing tiles
spriteBatch.End(); //End the camera spritebatch
// After this you can make another spritebatch without a camera to draw UI and things that will not move
I added the zoom and rotation if you want to add anything fancy, Just replace the variables.
That should get you started on it.
However, You will want to make sure the camera is in bounds, and make it follow.
Ill show you how to add smooth scrolling, However if you want simple scrolling see this sample.
private void ScrollCamera(Viewport viewport)
{
//Add to the camera positon, So we can see the origin
cameraPosition.X = cameraPosition.X + (viewport.Width / 2);
cameraPosition.Y = cameraPosition.Y + (viewport.Height / 2);
//Smoothly move the camera towards the player
cameraPosition.X = MathHelper.Lerp(cameraPosition.X , Player.Position.X, 0.1f);
cameraPosition.Y = MathHelper.Lerp(cameraPosition.Y, Player.Position.Y, 0.1f);
//Undo the origin because it will be calculated with the Matrix (I know this isnt the best way but its what I had real quick)
cameraPosition.X = cameraPosition.X -( viewport.Width / 2);
cameraPosition.Y = cameraPosition.Y - (viewport.Height / 2);
//Shake the camera, Use the mouse to scroll or anything like that, add it here (Ex, Earthquakes)
//Round it, So it dosent try to draw in between 2 pixels
cameraPosition.Y= (float)Math.Round(cameraPosition.Y);
cameraPosition.X = (float)Math.Round(cameraPosition.X);
//Clamp it off, So it stops scrolling near the edges
cameraPosition.X = MathHelper.Clamp(cameraPosition.X, 1f, Width * Tile.Width);
cameraPosition.Y = MathHelper.Clamp(cameraPosition.Y, 1f, Height * Tile.Height);
}
Hope this helps!

Categories