Moving objects with mousepicking

mcmillan0520

05-06-2010 23:16:51

Hi, I'm making an editor for my game in c#, and i've run into a problem trying to move objects by "sticking" them to the mouse. I think it's better explained with code:


//First of all, I'm picking an entity with MMOC, and getting the distance to it.
Pair<Entity, float> PickEntityDist(MouseEventArgs arg)
{
Vector2 mouse = new Vector2(arg.X, arg.Y);
CollisionTools.RaycastResult res;
res = mCollision.RaycastFromCamera(mWindow, mCamera, mouse, (uint)QueryFlags.Entity);
if (res != null)
return new Pair<Entity,float>(res.Target, res.Distance);
else
return new Pair<Entity,float>(null, 0.0f);
}


//Then in my MouseDown i want to construct a plane parallel to the viewport at the object, and only move that object along that plane
void Render_MouseDown(object sender, MouseEventArgs e)
{
Entity ent;
Pair<Entity,float> pair;
switch (mCurrentTool)
{
case Tools.Select:
(...)
break;
case Tools.Move:
pair = PickEntityDist((MouseEventArgs)e);
if (pair.first == null)
{
Deselect();
break;
}
else
{
Select(pair.first);
}
mMoving = true;

//Calculate vector between camera and object
Vector3 between = mCamera.DerivedPosition - mSelected.GetEntity().ParentNode._getDerivedPosition();

//Construct a plane for movement
mMovePlane = new Plane(between, pair.second);
break;




}

}

//Then in MouseMove i want to move the object, i do this by raycasting the mouse to the plane and moving the node to the point of intersection
void Render_MouseMove(object sender, MouseEventArgs e)
{
if (mRotating)
{
(...)
}
if (mMoving)
{

float tx = e.X / mWindow.Width;
float ty = e.Y / mWindow.Height;
Ray ray = mCamera.GetCameraToViewportRay(tx, ty);
Pair<bool, float> pair = ray.Intersects(mMovePlane);
if (pair.first)
mSelected.GetEntity().ParentNode.Position = ray.GetPoint(pair.second);
}

}



However when i try this, my object moves off just outside the top left corner of the viewport, and I cannot select it anymore.
What am I doing wrong? Any help would be appreciated :D