I created a project to replicate the issue I’m having. I have a working example of world to screen with sprite.js that works but i would prefer to use Playcanvas’ Elements instead.
Script is fairly straight forward
var elementPos = new pc.Vec3(); this.mainCam.camera.worldToScreen(this.worldObject.getPosition(),elementPos);
The element seems to completley disappear.
What am i doin wrong?
The issue is you are mixing two coordinate systems. When you read the screen position of the worldObject:
You receive back coordinates in pixels. However, when you set the position of UiElement:
You are setting it in world coordinates (much larger). In order to fix the problem, you should put your image element under a 2D screen and use setLocalPosition() instead in order to set the location in pixels.
cheers that makes sense, Hmm just tried this, does not seem to work. im now setting the local position instead, but still seems to disappear. i may be doing something obviously wrong
It took me a while to figure out too, but the issue is that (0,0) for the image element is in the center of the screen whereas (0,0) for the mouse is in the bottom left corner, causing the image to always end up off the screen. You can fix this by changing the anchor of the element to all 0’s.
Thanks! That seems to work now, but i am experiencing some strange behaviour. If i move the object in Z or Y the image seems to go in the opposite direction.
So if you set the top and bottom anchors to 1, and make the image’s y negative every time its position changes, it should work. In “screen” coordinates, a positive y is further down, which is why worldToScreen is returning a positive y-value, which is the opposite of what you would expect.
works perfectly thanks for all your help