How to rotate camera with mesh to always face the back of the mesh

#1

Hey,

I want my camera to always face the back of my mesh that I am rotation when “pointermove” event fires (basically a 3rd person view). How can I achieve this with Babylon cameras?

Also, right now, as said I am using pointermove to rotate my mesh. I would like to switch to pointer lock to get rid of the mouse and rotate the mesh based on mouse movements rather than picking points, any help on that please?

Thank you!
Fox

0 Likes

#2

Hey!

let’s start with question 1: You can consider attaching your camera to your mesh by setting camera.parent = mesh. The opposite could work as well depending on the effect you want to achieve. Also you could have a look at Cameras - Babylon.js Documentation

About Q2: Pointerlock will only hide the mouse cursor. Everything else works the same

0 Likes

#3

Hey Del,

Thanks, but does not work at all - the camera spins around 200 times when I move the mouse one pixel. It’s a top-down ish view and I control the Y rotation of the object by picking the pointer x and y from the scene and calculating the angles, so maybe that’s the issue?

Thx

0 Likes

#4

I will probably need to see the code to help further. Can you share a repro on the Playground?

0 Likes

#5

I can’t really, it’s already too big :frowning:

I’m gonna leave it like it is for now and come back to it later, thanks for the help so far!

1 Like

#6

Hey @Foxhoundn,

I use a freeCamera and always place it at the back of a mesh in this playground: https://playground.babylonjs.com/ts.html#0ZP9MH#4
See line 150

1 Like

#7

Thank you, that works a tiny bit better:

  1. In your demo the camera controls do not work, but in my game when I press left MB it’s trying to move and rotate etc, why? I don’t see anywhere that you have disabled the controls

  2. The camera still spins around a lot even if I move the mouse a tiny bit, also I move left and the camera turns right etc.

0 Likes

#8

In the playground I linked, I forget to remove the camera.attachControl(canvas, true); as it is not needed. The reason it does nothing is because I manually update the camera in the onBeforeRenderObservable to be behind the object so any rotation done by the attach control is just overwritten.

If you need to control the camera with mouse you can use onPointerObservable. See line 144 in this playground: https://playground.babylonjs.com/ts.html#0ZP9MH#5

0 Likes