[SOLVED] screenToWorld() functionality

tl;dr: Is there a screenToLocal() or something of the like that I can use? If not, will that functionality be available soon?

I gathered from the forums that you can only grab the mouse position when pc.EVENT_MOUSEMOVE is fired. It really sucks when you’re making a sidescrolling shooter since the camera gets stuck often because it’s connected to the mouse position.

I use screenToWorld() to grab the mouse position w.r.t. the world origin and use that to get the ray from the player to the mouse. So far it doesn’t seem like a compute-intensive approach but I think I can do better.

I’m thinking that since screenToWorld() needs to get the mouse position w.r.t the camera position for it to be able to compute for the mouse position w.r.t. the world, I could use that to get the mouse position w.r.t. the player if I make the camera a child of the player instead. Is there like a hidden function that would let me grab that instead? Thanks!

Here’s my current implementation: https://playcanvas.com/editor/scene/874238

ps I’m going to try to make an empty Entity a child of the player and have it lookAt() the mouse position and grab the angle from that if my current approach doesn’t work out. :joy: :ok_hand:


I think I may not have understood what exactly you are after, but regarding getting the mouse pos only when the mouse has moved, yes, that is true.

But that doesn’t mean you can’t know the mouse pos per frame, since if the mouse hasn’t moved, the mouse cursor position won’t change.

So you can just buffer the last coordinates the mouse cursor was in a vector and use that for your calculations.

var Mouse = pc.createScript('mouse');

Mouse.prototype.initialize = function() {
   this.mousePos = new pc.Vec2();

   this.app.mouse.on(pc.EVENT_MOUSEMOVE, this.onMouseMove, this);

Mouse.prototype.update = function(dt) {
  console.log(this.mousePos.x, this.mousePos.y);

Mouse.prototype.onMouseMove = function (event) {
   this.mousePos.set(event.x, event.y);
1 Like

Oh wow, I didn’t think of that. It works now and the camera isn’t jerking around. Thanks!

1 Like

Is there also a way to get the position of the mouse without a event? Or with a event when the mouse button is hold, so not only when pressed?

Without an event no, but the mouse move event will fire whichever button is pressed, or not.