Offsetting player camera

Recommended Posts

It's been a while since I've coded anything for MTA or done any math even remotely hard.

I have a player in a vehicle at (0, 0). The player is facing ahead at (5, 7). I want to move the player's camera to be at (-7, 5) or (7, -5) (not facing, the origin of the camera, like an offset). The player is able to look ahead fine without problems and the vertical levelling, but I can't seem to get it to offset properly. So far, the camera rotates around in a weird way and cuts around. Sometimes even in a circular motion.

I have tried offsetting the camera's X and Y positions using perpendicular vectors (as demonstrated in the above picture). That didn't work.

```	-- forceSide is a variable between 0.5 and -0.5 toggleable by a user
-- Yeah, all this is running in an onClientRender event

local forceSide = 0.3 -- For example
local camPosX, camPosY, camPosZ = getPedBonePosition(localPlayer, 6)
local rx, ry, rz = getElementRotation(getPedOccupiedVehicle(localPlayer))
local theta = (math.atan2(camPosY, camPosX) * (180 / math.pi) + 360) % 360

local nTheta
if (forceSide > 0) then
nTheta = (theta + 90) % 360
elseif (forceSide < 0) then
nTheta = (theta - 90) % 360
end

local perp
if nTheta then
local lX = forceSide * math.cos(nTheta)
local lY = forceSide * math.sin(nTheta)

perp = Vector2(lX, lY)
end

if perp then
local c = Vector2(camPosX, camPosY)
if (forceSide > 0) then
c = c + (perp * math.abs(forceSide))
elseif (forceSide < 0) then
c = c + (perp * math.abs(forceSide))
end
camPosX, camPosY = c.x, c.y
end

-- All these other variables are of no concern
setCameraMatrix(camPosX, camPosY, camPosZ + forceHigh, camTargetX, camTargetY, camTargetZ, roll)```

This code is messy but it's what I've currently got. I have used other methods to get the vectors to be perpendicular but also to no avail.

What I want to do is for the player's camera to move horizontally out of the vehicle, but stay directly beside the vehicle (this is all in a cockpit view) no matter the rotation, coordinates etc.

So it's basically offsetting the player's camera, but maintaining that it's looking forward and what not. Like that view where you see the front side fender and wheel of your car.

Thanks.

Edited by Noki
```local x, y, z = getElementPosition(player)
local cx, cy, cz = getElementPosition(player)
roll = -0.8*math.deg(math.asin(z))
local player = getElementPosition(getLocalPlayer())
setCameraMatrix(x-0.55, y+1, z+0.5, cx-0.55, cy-0.2, cz+0.55, roll)```

Edited by Debo15

Check the examples of this function:

No complex math required. Just getting 2x the offset of the vehicle and using it as camera start and end point.

Create an account

Register a new account