Make camera move toward entity

https://playcanvas.com/editor/code/951293?tabs=98533706
https://playcanvas.com/editor/scene/1458391
How do I make the camera move toward the target entity when the target is clicked? I think I’m fairly close, but I can’t really get further with my limited knowledge

Hi @MoonAlien822,

Try studying the following example, it shows how to animate an entity moving towards a target:

https://developer.playcanvas.com/en/tutorials/point-and-click-movement/

That entity can be the camera.

Is it possible to make it react only to certain targets, like objects in the scene?

Yes, in the example I posted the animation path is calculated from the current entity position towards a target entity position.

You can filter the target selection to be only certain targets. For entity picking check some of the examples here:

https://developer.playcanvas.com/en/tutorials/?tags=raycast

1 Like

@Leonidas I tried copying it directly which I didn’t expect to work and it didn’t but idk how to fix it.

I get the following error when clicking:

[point-and-click.js?id=101422752&branchId=45859137-3b45-4048-8256-6bae471552d7:107]: Uncaught TypeError: Cannot read properties of undefined (reading ‘screenToWorld’)

TypeError: Cannot read properties of undefined (reading ‘screenToWorld’)
at PointAndClick.doRayCast (https://launch.playcanvas.com/api/assets/files/Scripts/point-and-click.js?id=101422752&branchId=45859137-3b45-4048-8256-6bae471552d7:107:30)
at PointAndClick.onMouseDown (https://launch.playcanvas.com/api/assets/files/Scripts/point-and-click.js?id=101422752&branchId=45859137-3b45-4048-8256-6bae471552d7:85:14)
at Mouse.fire (https://code.playcanvas.com/playcanvas-1.56.0.dbg.js:743:21)
at Mouse._handleDown (https://code.playcanvas.com/playcanvas-1.56.0.dbg.js:53485:11)

https://playcanvas.com/editor/scene/1458391

Hey @MoonAlien822,

Taking a look at your scene, your Root entity, containing the pointAndClick script has a Camera variable which I think you accidentally dragged your player entity to instead of your Camera entity. I’ve simply dragged the Camera entity into the variable and it works.
Screenshot 2022-09-12 at 09.55.32

1 Like

@poliveira the error is now gone! still not zooming though

1 Like

Hey @MoonAlien822,

I’ve altered your script with a few changes that makes it so that the camera zooms in at the location of the users’ click.

What I’m doing is basically

  1. Raycasting from the camera to the location to where the mouse clicked
  2. Setting the raycast’s result point as the new focus position for the camera
  3. Halving the distance from the camera to the focus point (With a minimum distance)

For that to work, I’ve also added a Sphere Collider and Rigidbody to the planet. Please look at the example project here. All the changes I’ve done are located in the camera.js script. You might want to take a look at doRaycast, in line 186.

1 Like

thanks! I’ll check out what you did

1 Like