Rotated camera how to go forward in camera viewpoint?

Godot Version

Latest

Question

I have a camera3D node I rotate with:

camera.rotation.y += 1.0

When I press W it goes forward in the world forward direction, but I want it to go forward in the forward camera direction.

My go forward code is:

(moveup is set to 1 when W is pressed)

if moveup == 1:
    camera.global_position.z -= 1.0

How can I make it move forward from the camera forward direction and not the world forward direction?

Use the camera.global_basis to transform your direction, like so: camera.global_basis * Vector3(0, 0, 1) for example

I tried:

camera.global_position.z -= camera.global_basis * Vector3(0,0,1) * scrollspeed

But now it errors:

Invalid operands 'float' and 'Vector3' in operator '-'.

You should just assign the global position, not just z

So, what I actually wanted to do was an RTS style camera, it’s angled down to see the map, but forward moves forward but not towards where the camera is actually facing…so in the plane of the map kinda. Play an RTS and you’ll understand what I mean!

Anyway, here’s my final working code:

if moveup == 1: velocity -= self.basis.z - Vector3(0, self.basis.z.y, 0)
if movedown == 1: velocity += self.basis.z - Vector3(0, self.basis.z.y, 0)
if moveleft == 1: velocity -= self.basis.x
if moveright == 1: velocity += self.basis.x
velocity = velocity.normalized()
self.global_translate(velocity * delta * movement_speed)

Left and right is fine, but for up and down you need to delete the y component of the vector from itself to zero it out (so the effect of the camera looking down is ignored) leaving only the x and z parts of the vector for up/down motion.

If you put this script not (on your camera node) then you can replace “self” with your camera location: $MYCAMNAME or whatever like: $MyCam1.basis.z etc.

Lastly, note the double vector location thing on: self.basis.z.y: because basis is 3 vector3’s, then basis.z returns a single vector3, then you take the y component of that which is a single value.

Edit: Replaced transform.basis to just basis based on feedback below. Code checked and confirmed working the same.

1 Like

You should probably just take the direction of the body not the camera itself that’s facing up and down

You also don’t need transform.basis you just take basis

You can also simply use basis * Vector3.FORWARD, basis * Vector3.LEFT, and basis * Vector3.RIGHT to make it clearer

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.