I'm currently trying to implement a physics gun for my game. What I want is for the entity to stay in the same position on the screen no matter how I wiggle the camera about, what is the correct way to achieve this?

I threw together a basic physics gun in 5 minutes (just to handle grabbing and moving the object) but it doesn't work as intended. The problem is obviously that I only handle changes in toolDirection (rotation) but largely ignore changes in toolPosition (translation). For reference, here is my current script (wrtten in Lua):

local toolPosition; --This always holds the position of the tool
local toolDirection; --This always holds a normalized vector indicating the direction the tool is pointing
local grabLocation; --This is the position in world space where the ray from the tool intersected the body of the entity

function UpdateTargetPosition()
    local relativeGrabDirection = (grabLocation - toolPosition).Normalize();                 --direction from tool to target grab point

    local axis = relativeGrabDirection.Cross(toolDirection);
    local angle = math.acos(relativeGrabDirection.Dot(toolDirection));
    local rotation = Quaternion.CreateFromAxisAngle(axis, angle);

    local transform = Matrix4x4.CreateTranslation(-toolPosition) * Matrix4x4.CreateFromQuaternion(rotation) * Matrix4x4.CreateTranslation(toolPosition);
    target.SetWorldTransform(target.GetWorldTransform() * transform);
    grabLocation = grabLocation.TransformByMatrix4x4(transform);
  • 2
    \$\begingroup\$ Doesn't work at all? Looks like a pretty good go for 5 minutes. So you already know what you need to do, what are you looking for from us? \$\endgroup\$ – MichaelHouse Jan 18 '13 at 15:42
  • \$\begingroup\$ I know I need to handle translation, but I'm not sure exactly what the problem is that's causing rotation when I translate in the current version. Of course if I don't know that, then I don't know how I need to change the transform matrix to fix it :( \$\endgroup\$ – Martin Jan 18 '13 at 16:10
  • \$\begingroup\$ I still don't understand what you want to do. \$\endgroup\$ – Anko Dec 14 '14 at 21:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.