I was trying to create a sample pixi application. Where I had an image, when user clicks on the image, it should move its position.
var canvasWidth = window.innerWidth;
var canvasHight = window.innerHeight
var renderer = PIXI.autoDetectRenderer(canvasWidth, canvasHight);
document.body.appendChild(renderer.view);
var stage = new PIXI.Container();
PIXI.loader
.add('images/sample.png')
.add('images/background.jpg')
.load(setup);
function setup() {
var backGround = new PIXI.Sprite(
PIXI.loader.resources["images/background.jpg"].texture);
var steve = new PIXI.Sprite(
PIXI.loader.resources["images/sample.png"].texture);
backGround.hieght = canvasHight;
backGround.width = canvasWidth;
setPropertiesToSteve(steve);
stage.addChild(backGround);
stage.addChild(steve);
renderer.render(stage);
}
// Function just to set properties for steve
function setPropertiesToSteve(steve) {
steve.interactive = true;
steve.position.x = canvasWidth/2;
steve.position.x = canvasWidth/4;
steve.on('pointerdown',function(){
steve.position.x = steve.position.x + 10;
});
}
But when I click on the object nothing happening. I am very much new to pixijs.SO don't know how to handle this.
You need to render the stage again :)
Take a look at the official Pixi examples https://pixijs.github.io/examples/
They use the PIXI.Application class which sets up common things like a ticker that automatically re renders your stage
Related
My old project is developed using Createjs. I need to scaleout movieclip but it's not scaling it's child objects.
let stage = new createjs.Stage('canvas2');
stage.mouseMoveOutside = true;
stage.enableMouseOver(30);
let mc = new createjs.MovieClip();
let circle = new createjs.Shape(
new createjs.Graphics().beginFill("#999999").drawCircle(0,0,100)
);
mc.addChild(circle)
stage.addChild(mc)
let img = new Image();
img.src="images/testimages/we2.jpg";
img.onload=(e)=>{
let b = new createjs.Bitmap(e.target);
mc.addChild(b);
mc.scale=.2;
setTimeout(()=>{
mc.scale=.2;
},1000)
}
window.createjs.Ticker.addEventListener('tick',function(e){
stage.update(e);
})
I need to scale Movieclip after loading image but it's doing nothing.
Instead of using mc.scale=.2;, if I chain the X and Y settings then it works:
mc.scaleX = mc.scaleY = 0.2;
I am making a battleship game with polar coordinates. After the user chooses two points, a battleship should be drawn in the middle. My Battleship constructor looks like this:
function Battleship(size, location, source){
this.size = size;
//initializing the image
this.image = new Image();
this.image.src = source;
this.getMiddlePoint = function(){
//get midpoint of ship
...
}
this.distanceBetween = function(t1, t2){
//dist between two points
}
this.display = function(){
var point = [this.radius];
point.push(this.getMiddlePoint());
point = polarToReal(point[0], point[1] * Math.PI / 12);
//now point has canvas coordinates of midpoint
var width = this.distanceBetween(this.info[0][0], this.info[this.info.length-1][0]);
var ratio = this.image.width / width;
ctx.drawImage(this.image, point[0] - width/2, point[1] - this.image.height / ratio / 2, width, this.image.height / ratio);
//draws the image
}
}
The display method of each ship gets called at a certain point (after the user has chosen the location). For some reason, the images do not show the first time I do this, but when I run this code at the very end:
for(var i = 0; i<playerMap.ships.length; i++){
playerMap.ships[i].display();
}
All ships are displayed correctly (not aligned well, but they are displayed). I think there is a problem with loading the images. I am not sure how to fix this. I tried using image.onload but I never got that to work. I also tried something like this:
var loadImage = function (url, ctx) {
var img = new Image();
img.src = url
img.onload = function () {
ctx.drawImage(img, 0, 0);
}
}
but the same problem kept happening. Please help me fix this problem. Here is the game in its current condition. If you place ships, nothing happens, but after you place 5 (or 10) ships, they suddenly all load.
EDIT:
I solved the problem by globally defining the images. This is still very bad practice, since I wanted this to be in the battleship object. This is my (temporary) solution:
var sub = [];
for(var i = 1; i<5; i++){
sub[i] = new Image();
sub[i].src = "/img/ships/battleship_"+i+".png";
}
I had drawn an animation in canvas like this and rendered a map using openlayers4. I want to add this canvas to the map[openlayers canvas] in next step.
I had used ol.source.ImageCanvas add a boundary to openlayers, so I try to add the canvas with animation using ImageCanvas, but failed.
What's more, openlayers API said ol.source.ImageCanvas method only the image canvas can be added. I didn't know whether the animate canvas so does.
Should I insit on using ImageCanvas method or try others?
Can someone give me an example if I abandon the ImageCanvas method?
After some tries, I got a solution! Haha!
First: the ol.source.ImageCanvas can still use, but you will get a stopped animate just like a screenshot.
Second: must know the ol.map.render() in openlayers3 or openlayers4, whose description is:
Request a map rendering (at the next animation frame).
Thus, you can use it to refresh the map and get the next animation of canvas.
The following is snippets of my code:
var topoCanvas = function(extent, resolution, pixelRatio, size, projection) {
// topo features;
var features = topojson.feature(tokyo, tokyo.objects.counties);
var canvasWidth = size[0];
var canvasHeight = size[1];
var canvas = d3.select(document.createElement('canvas'));
canvas.attr('width', canvasWidth).attr('height', canvasHeight);
var context = canvas.node().getContext('2d');
var d3Projection = d3.geo.mercator().scale(1).translate([0, 0]);
var d3Path = d3.geo.path().projection(d3Projection);
var pixelBounds = d3Path.bounds(features);
var pixelBoundsWidth = pixelBounds[1][0] - pixelBounds[0][0];
var pixelBoundsHeight = pixelBounds[1][1] - pixelBounds[0][1];
var geoBounds = d3.geo.bounds(features);
var geoBoundsLeftBottom = ol.proj.transform(geoBounds[0], 'EPSG:4326', projection);
var geoBoundsRightTop = ol.proj.transform(geoBounds[1], 'EPSG:4326', projection);
var geoBoundsWidth = geoBoundsRightTop[0] - geoBoundsLeftBottom[0];
if (geoBoundsWidth < 0) {
geoBoundsWidth += ol.extent.getWidth(projection.getExtent());
}
var geoBoundsHeight = geoBoundsRightTop[1] - geoBoundsLeftBottom[1];
var widthResolution = geoBoundsWidth / pixelBoundsWidth;
var heightResolution = geoBoundsHeight / pixelBoundsHeight;
var r = Math.max(widthResolution, heightResolution);
var scale = r / (resolution / pixelRatio);
var center = ol.proj.transform(ol.extent.getCenter(extent), projection, 'EPSG:4326');
d3Projection.scale(scale).center(center).translate([canvasWidth / 2, canvasHeight / 2]);
d3Path = d3Path.projection(d3Projection).context(context);
d3Path(features);
context.stroke();
// above code is add a topoJson boundary to canvas
// below code is add an animation to canvas
var settings = createSettings(tokyo, {
width: canvasWidth,
height: canvasHeight
});
// reset the projection and bounds for animation canvas
settings.projection = d3Projection;
settings.bounds = geoBounds;
var mesh = buildMeshes(tokyo, settings);
when(render(settings, mesh, {
width: canvasWidth,
height: canvasHeight
})).then(function(masks) {
when(interpolateField(stations, data, settings, masks)).then(function(field) {
// wind moving animation
animate(settings, field, canvas);
// refresh the map to get animation
window.setInterval(function() {
map.render();
}, 50);
});
});
return canvas[0][0];
}
I made a scene in Blender that I exported into a .babylon, and now I am importing it into the game. The map is 351KB, and I am loading it into the game like this:
var BABYLON;
var canvas = document.getElementById('gamecanvas');
var engine = new BABYLON.Engine(canvas, true);
var scene = new BABYLON.Scene(engine);
var light = new BABYLON.PointLight('light', new BABYLON.Vector3(0,0,10), scene);
var player = new BABYLON.FreeCamera('player', new BABYLON.Vector3(1,1,1), scene); //IMPORTANT LINE
var player_height = 2;
var player_speed = 1;
var player_inertia = 0.9;
var mouse_position = new BABYLON.Vector2(mouse_position.x, mouse_position.y);
function INIT_GAME(){
engine.runRenderLoop(function(){ //IMPORTANT LINE
scene.render();
});
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
canvas.requestPointerLock = canvas.requestPointerLock || canvas.mozRequestPointerLock;
canvas.requestPointerLock();
scene.enablePhysics(); //IMPORTANT LINE
scene.setGravity(new BABYLON.Vector3(0, -10, 0)); //IMPORTANT LINE
player.attachControl(canvas, true); //IMPORTANT LINE
player.ellipsoid = new BABYLON.Vector3(1, player_height, 1);
player.checkCollisions = true;
player.applyGravity = true;
player.keysUp = [87];
player.keysDown = [83];
player.keysLeft = [65];
player.keysRight = [68];
player.inertia = player_inertia;
player.speed = player_speed;
window.addEventListener('resize', function(){
engine.resize();
});
BABYLON.SceneLoader.Load('Scenes', 'zombie_map.babylon', engine); //IMPORTANT LINE
}
I've attempted to narrow everything down to what you should need to look at, but I left it all there just in case there was something I missed. (INIT_GAME is loaded on page load). My problem is, I think the scene is loading, but it just gives me a strange loading icon, which I presume is just Babylon trying to load in the scene I passed it. My questions are:
Am I loading everything in properly?
What is the proper format to import a .babylon scene?
Is the size of the map too big for the browser, and if so, how can I compress it?
I can provide a link to the site if you need to see the results head-on. Let me know, thanks!
I think the solution is very simple.
Add a slash after your rootURL.
So replace
BABYLON.SceneLoader.Load('Scenes', 'zombie_map.babylon', engine); //IMPORTANT LINE
with
BABYLON.SceneLoader.Load('Scenes/', 'zombie_map.babylon', engine); //IMPORTANT LINE
Try this and let me know how it goes.
The Problem
I am finding it rather difficult to get my head around this, I am attempting to move an image using the mouse along the X axis only. I am finding it hard to even move the image at all and the many tutorials I have looked at arnt really helping me. Here is what I am trying to say:
As you can see by my beautiful image above I only want to image to move left and right at the bottom of the page.
The Code and the Question
Here is my first attempt, when I try this all the images loaded on the canvas no longer appear making it very hard for me to understand why it isnt working.
<script type="text/javascript">
//Referencing the canvas
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var width = canvas.getAttribute('width');
var height = canvas.getAttribute('height');
//Images
var bggameImage = new Image();
var playerImage = new Image();
var enemyImage = new Image();
var projectileImage = new Image();
var livesImage = new Image();
//Canvas dimensions
var width = 480;
var height = 320;
//Loading in the backgroundImage
bggameImage.src = "Images/bggameImage.png";
bggameImage.onload = function(){
context.drawImage(bggameImage, 0, 0);
}
//Loading in the playerImage
playerImage.src = "Images/playerImage.png";
playerImage.onload = function(){
context.drawImage(playerImage, 165, 240);
}
//Loading in the projectileImage
projectileImage.src = "Images/projectileImage.png";
projectileImage.onload = function(){
context.drawImage(projectileImage, 65, 240);
}
var playerImage = {
x:176,
y:74,
}
function init() {
playerImage.src = "Images/playerImage.png";
//Moving player
myCanvas.addEventListener("mousemove", function (e) {
var bounding_box = myCanvas.getBoundingClientRect();
playerImage = (e.clientX - bounding_box.left) * (myCanvas.width / bounding_box.width) - playerImage.width / 2;
playerImage = (e.clientY - bounding_box.top) * (myCanvas.height / bounding_box.height) - playerImage.height / 2;
}
)
</script>
The whole "function init()" part is what I have just tried but I thought I would include this anyway, I understand that I am loading in the playerImage twice.
You're using the same variable name twice (playerImage), so your image is being overwritten. You're using it for the image and also to store the position. Change the playerImage that's storing x and y to be playerPosition or something like that. Update that variable on your mouse event and then render the image according to that variable's values.
Ultimately, you're going to have to look at a game loop using setTimeout or requestAnimationFrame. So, this will become crucial at that stage. And yes, you shouldn't be loading the player image twice either. Do all of that at the start and only start your game when all your assets have successfully loaded.
For instance...
var playerImage;
var alienImage;
var bulletImage;
var assetCount = 0;
function loadAssets() {
playerImage = new Image();
playerImage.onload = checkAssetsLoaded;
playerImage.src = "assets/images/Brush01.png";
alienImage = new Image();
alienImage.onload = checkAssetsLoaded;
alienImage.src = "assets/images/Brush02.png";
bulletImage = new Image();
bulletImage.onload = checkAssetsLoaded;
bulletImage.src = "assets/images/Brush03.png";
}
function checkAssetsLoaded(event) {
assetCount++;
console.log("An asset has loaded!: " + assetCount);
if (assetCount == 3) {
startGame();
}
}
function startGame() {
// Start your game initialization logic here.
console.log("Game starting!");
}