# How do I tie an object to the mouse? (with playground example)

**URL:** <https://forum.babylonjs.com/t/how-do-i-tie-an-object-to-the-mouse-with-playground-example/7799>\
**Category:** Questions\
**Created:** [December 30, 2019, 7:40pm UTC](https://forum.babylonjs.com/t/how-do-i-tie-an-object-to-the-mouse-with-playground-example/7799 "2019-12-30T19:40:42Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Kochab](https://avatars.discourse-cdn.com/v4/letter/k/a88e57/32.png) [@Kochab](https://forum.babylonjs.com/u/Kochab)\
**Post date:** [December 30, 2019, 7:40pm UTC](https://forum.babylonjs.com/t/how-do-i-tie-an-object-to-the-mouse-with-playground-example/7799/1 "2019-12-30T19:40:42Z")

</div>

I’m trying to move a sphere with the mouse. I want the sphere’s Z to always be 0 and I want it to always be directly under the mouse. I’m using this Three.js example code on Stack Overflow as a guide:

> <https://stackoverflow.com/questions/13055214/mouse-canvas-x-y-to-three-js-world-x-y-z/13091694#13091694>

I like that example because it doesn’t rely on any objects being in the scene. It just takes the screen coordinates and converts to world with a Z of 0. Other examples use `scene.pick` for this, but I’m not trying to pick any objects and don’t really like the idea of creating a plane at Z = 0 just to have a pick target.

Here is my code:  
[https://www.babylonjs-playground.com/#DVFUMS](https://www.babylonjs-playground.com/#DVFUMS)

which almost works, except the sphere is not under the mouse. I suspect I’m not using `Unproject` correctly as I did get this to work in Three.js.

---

<div class="post-metadata">

**Author:** ![Kochab](https://avatars.discourse-cdn.com/v4/letter/k/a88e57/32.png) [@Kochab](https://forum.babylonjs.com/u/Kochab)\
**Post date:** [December 31, 2019, 2:31am UTC](https://forum.babylonjs.com/t/how-do-i-tie-an-object-to-the-mouse-with-playground-example/7799/2 "2019-12-31T02:31:36Z")

</div>

Solved! For some reason I didn’t need the `* 2 + 1` and `* 2 - 1` bits.

I also decided to use engine render width and height rather than the inner window width and height. This code doesn’t work in the playground but does work with my full screen app.

```auto
window.addEventListener("mousemove", function (event) {
  event.preventDefault();
  if (!player) return;
  mouseVector.set((event.clientX / engine.getRenderWidth()), (event.clientY / engine.getRenderHeight()), 0.5);
  let uvec = BABYLON.Vector3.Unproject(mouseVector, 1, 1, BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  var dir = uvec.subtract(camera.position).normalize();
  var distance = -camera.position.z / dir.z;
  var pos = camera.position.clone().add(dir.scale(distance));

  player.position = pos;
});

```
