I am trying to access a Sprite Asset in JavaScript code and change its position.
I attached below JavaScript source code to the camera:
var Main = pc.createScript('main');
// initialize code called once per entity
Main.prototype.initialize = function() {
console.log("running!");
};
// update code called every frame
Main.prototype.update = function(dt) {
var entity = this.app.assets.find('BG_Black');
entity.setPosition(130, 130, 1); // "entity" is NULL ?
};
// uncomment the swap method to enable hot-reloading for this script
// update the method body to copy state from the old instance
// Main.prototype.swap = function(old) { };
// learn more about scripting here:
// https://developer.playcanvas.com/user-manual/scripting/
Hoping someone knows how to make the above work?
Thanks!
I cleared the error by naming the Sprite to: “BG_Black”.
But when I modify the position to any value the Sprite is not shown?
SS
// update code called every frame
Main.prototype.update = function(dt) {
var entity = this.app.root.findByName('BG_Black');
entity.setPosition(130, 130, 0);
};
NOTE #1:
I now understand position is in a range of -1 to 1 ?
But setting the position to (0.75, 0.75, 0) still shows the Sprite centered on the screen?
The sprite is black and when you press play you only see black. Currently the clear color of the camera is green, so that means you only see the sprite in front of the camera.
Just trying to learn how to manipulate a Sprite on the screen.
I don’t fully understand how to change x, y of the Sprite on the screen.
(through JavaScript code)
I did a quick check on my laptop today and noticed that the camera is positioned on the same line as your sprite. Because of this, the sprite isn’t rendered, because it’s not in front of the camera. Moving the camera slightly back on the z axis solved this issue.
When setting the position by script, a value of 6.5 is enough to reach the edge of my screen. So the value of 20 I previously suggested was actually too high as well.
I don’t understand at all the coordinate system for moving 2D Sprite though.
Is there a method to convert to pixels on the screen?
(screen is: 1280x720)
Unfortunately, I’m not an expert in that either and I’m still not entirely sure what you’re trying to achieve. Without a clear goal, it’s hard to fully understand everything right away.
Maybe searching through the documentation and forum can help you along the way.