Phaser Draggable Grouped World Map - javascript

I found this great tutorial on creating draggable maps with inertia: http://www.emanueleferonato.com/2016/01/18/how-to-create-a-html-draggable-and-scrollable-map-with-inertia-using-phaser-framework/
The tutorial has the dragging effect applied on just an image. I'm trying to have the dragging effect applied on a group of sprites instead, so they would all drag at the same time (map image + group of sprites).
The issue I have is that I'm a little confused about what this.scrollingMap represents syntax-wise. So when it comes to replacing this line with a group, I'm a little lost.
this.scrollingMap = game.add.image(0, 0, "map");
Anyone have any ideas?
I copied the simplified code below as well if that helps.
var game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO, '', { preload: preload, create: create, update: update });
function preload() {
game.load.image('map', 'assets/images/baseMap.png');
game.load.image('star', 'assets/images/star.png');
}
function create() {
// Creating the group
world = game.add.group();
world.create(0, 0, 'map');
// Adding random sprites to it
for (var i = 0; i < 10; i++)
{ world.create(game.world.randomX, game.world.randomY, 'star');}
//This group works on its own.
//I would like to link it to the dragging animation below "scrollingMap".
//The Draggable Map from the tutorial
// Adding the big map to scroll
this.scrollingMap = game.add.image(0, 0, "map"); //<-- This is where I am having trouble changing from an image to a group.
// map will accept inputs
this.scrollingMap.inputEnabled = true;
// map can be dragged
this.scrollingMap.input.enableDrag(false);
// custom property: we save map position
this.scrollingMap.savedPosition = new Phaser.Point(this.scrollingMap.x, this.scrollingMap.y);
// custom property: the map is not being dragged at the moment
this.scrollingMap.isBeingDragged = false;
// custom property: map is not moving (or is moving at no speed)
this.scrollingMap.movingSpeed = 0;
// map can be dragged only if it entirely remains into this rectangle
this.scrollingMap.input.boundsRect = new Phaser.Rectangle(game.width - this.scrollingMap.width, game.height - this.scrollingMap.height, this.scrollingMap.width * 2 - game.width, this.scrollingMap.height * 2 - game.height);
// when the player starts dragging...
this.scrollingMap.events.onDragStart.add(function(){
this.scrollingMap.isBeingDragged = true;
// set movingSpeed property to zero. This will stop moving the map
// if the player wants to drag when it's already moving
this.scrollingMap.movingSpeed = 0;
}, this);
// when the player stops dragging...
this.scrollingMap.events.onDragStop.add(function(){
this.scrollingMap.isBeingDragged = false;
}, this);
} //End create function
function update() {
// if the map is being dragged...
if(this.scrollingMap.isBeingDragged){
this.scrollingMap.savedPosition = new Phaser.Point(this.scrollingMap.x, this.scrollingMap.y);
}
// if the map is NOT being dragged...
else{
// if the moving speed is greater than 1...
if(this.scrollingMap.movingSpeed > 1){
this.scrollingMap.x += this.scrollingMap.movingSpeed * Math.cos(this.scrollingMap.movingangle);
this.scrollingMap.y += this.scrollingMap.movingSpeed * Math.sin(this.scrollingMap.movingangle);
if(this.scrollingMap.x < game.width - this.scrollingMap.width){
this.scrollingMap.x = game.width - this.scrollingMap.width;
}
if(this.scrollingMap.x > 0){
this.scrollingMap.x = 0;
}
if(this.scrollingMap.y < game.height - this.scrollingMap.height){
this.scrollingMap.y = game.height - this.scrollingMap.height;
}
if(this.scrollingMap.y > 0){
this.scrollingMap.y = 0;
}
this.scrollingMap.movingSpeed *= friction;
// save current map position
this.scrollingMap.savedPosition = new Phaser.Point(this.scrollingMap.x, this.scrollingMap.y);
}
// if the moving speed is less than 1...
else{
var distance = this.scrollingMap.savedPosition.distance(this.scrollingMap.position);
var angle = this.scrollingMap.savedPosition.angle(this.scrollingMap.position);
if(distance > 4){
this.scrollingMap.movingSpeed = distance * speedMult;
this.scrollingMap.movingangle = angle;
}
}
}
}

So, I ended up finding the solution...
First off, I removed all this.scrollingMap and changed them to scrollingMap to remove any confusion. Ended up stil working perfectly.
scrollingMap = game.add.image(0, 0, "map");
scrollingMap.anchor.set(0.05,0.5);
scrollingMap.inputEnabled = true;
[etc...]
Next, Groups in Phaser don't seem to be able to have input working on elements together, only one at a time. So changing to something like wouldn't work:
scrollingMap = game.add.group();
map = game.add.image(0, 0, "map");
scrollingMap.add(map);
// The following line won't work
scrollingMap.inputEnabled = true;
I tried using the Align functions that Phaser offers... Until I ended up realising that you can actually nest sprites within other sprites like so:
scrollingMap = game.add.image(0, 0, "map");
someSprite = game.add.image(100, 100, "sprite");
scrollingMap.addChild(someSprite);
And voila! There's the solution, as simple as that.
Note that you can also add groups as children:
someGroup = game.add.group();
scrollingMap.addChild(someGroup);
Found the solution here if anyone's curious:
http://www.html5gamedevs.com/topic/7745-move-a-group-of-sprites-together-as-one-body/

Related

How to create objects on runtime and move them?

I'm trying to create objects on my game update and move them. This is my banana object:
function Banana() {
this.height = 1.96;
this.width = 3.955;
this.pos_x = CENTER - this.width/2;
this.pos_y = -475;
this.banana_image = banana_image;
};
And this is the Move method:
Banana.prototype.move = function(){
if (this.pos_y > 500) {
//this.banana_image.parentElement.removeChild(this.banana_image);
}
this.height += ZOOM_RATE;
this.width += ZOOM_RATE;
this.pos_y += 3;
this.pos_x -= SIDES_RATE;
};
This is the Game Update part:
Game.update = function() {
this.player.move();
//creating bananas
if (objs.lenght <= 0) {
this.banana = new Banana();
} else {
for (i = 0; i < 10; i++) {
objs.push(new Banana());
}
}
//moving bananas
for (i = 0; i < objs.lenght; i++) {
this.objs[0].move();
}
};
Game Draw:
function Game.draw = function() {
this.context.drawImage(road, 0,0, rw, rh);
this.context.drawImage(
this.player.player_image,
this.player.pos_x, this.player.pos_y,
this.player.width, this.player.height);
this.context.drawImage(
this.banana.banana_image,
this.banana.pos_x, this.banana.pos_y,
this.banana.width, this.banana.height);
};
I tried to ask this to multiple people, but I can't find an answer for it.
Let's say you want to move the objects 10 times and then stop.
First you need to add a line to the start of Game.draw, so that it clears the canvas making you always start drawing from scratch:
this.context.clearRect(0,0,500,500); // clear canvas, adjust box size if needed
Then make a function to call both update and draw, and queue that function to be called again:
var count = 10;
function updateAndDraw() {
Game.update();
Game.draw();
count--;
if (count) requestAnimationFrame(updateAndDraw);
}
// start moving:
requestAnimationFrame(updateAndDraw);
The movement may go too fast to your liking, so then adjust the move method to make smaller changes, or use setTimeout instead of requestAnimationFrame (but that will make the animation less fluent).
Note that you have a few errors in your code, which you will need to fix first:
lenght should be length
function Game.draw = function() {: remove function before Game.draw.
... check the error messages you get in console.

Pixi.js keeps accelerating on page refresh

These are my references created in pixi.js here:
http://brekalo.info/en/reference
If we go to references it loads pixiJS and everything works fine on first load! Then, if we go to another page let's say: http://brekalo.info/en/contact, and the go back to references again - now my references have accelerated text movement and rotation and it keeps accelerate on each reference page load!
Here is my javascript/pixi code below:
function initiatePixi() {
Object.keys(PIXI.utils.TextureCache).forEach(function(texture) {
PIXI.utils.TextureCache[texture].destroy(true);}
);
// create an new instance of a pixi stage
var container = new PIXI.Container();
// create a renderer instance.
renderer = PIXI.autoDetectRenderer(frameWidth, frameHeight, transparent = false, antialias = true);
// set renderer frame background color
renderer.backgroundColor = 0xFFFFFF;
// add the renderer view element to the DOM
document.getElementById('pixi-frame').appendChild(renderer.view);
// create references
createReferences(animate); // callback to animate frame
function createReferences(callback) {
// Create text container
textContainer = new PIXI.Container();
textContainer.x = 0;
textContainer.y = 0;
for (i = 0; i < references.length; i++) {
var style = {
font:"22px Verdana",
fill:getRandomColor()
};
var text = new PIXI.Text(references[i], style);
text.x = getRandomInteger(20, 440); // text position x
text.y = getRandomInteger(20, 440); // text position y
text.anchor.set(0.5, 0.5); // set text anchor point to the center of text
text.rotation = getRandomInteger(0, rotationLockDeg) * 0.0174532925; // set text rotation
// make the text interactive
text.interactive = true;
// create urls on text click
text.on("click", function (e) {
var win = window.open("http://" + this.text, '_blank');
win.focus();
});
textContainer.addChild(text);
rotateText(); // rotate text each second
}
container.addChild(textContainer);
// callback
if (callback && typeof(callback) === "function") {
callback();
}
}
function animate() {
requestAnimationFrame(animate);
// render the stage
renderer.render(container);
}
function rotateText() {
var rotateTimer = setInterval(function () {
for (var key in textContainer.children) { // loop each text object
var text = textContainer.children[key];
if(text.rotation / 0.0174532925 < -rotationLockDeg || text.rotation / 0.0174532925 > rotationLockDeg) {
if(text.rotation / 0.0174532925 < -rotationLockDeg)
text.rotation = -rotationLockRad;
if(text.rotation / 0.0174532925 > rotationLockDeg)
text.rotation = rotationLockRad;
rotation = -rotation;
}
text.rotation += rotation; // rotate text by rotate speed in degree
if(text.x < 0 || text.x > 460)
dx = -dx;
if(text.y < 0 || text.y > 460)
dy = -dy;
text.x += dx;
text.y += dy;
}
}, 75);
}
// get random integer between given range (eg 1-10)
function getRandomInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// random hex color generator
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
Thanks in advance!
:: cheers ::
Josip
To expand #Cristy's comment to an answer:
The answer lies in the same reason as why your question title is wrong: There is indeed NO page refresh when doing what you describe. If there were, you wouldn't have that problem in the first place. Try it out, hit F5 a few times on you animated page, it will stay the same speed.
The reason is that you are running a angular based single page application, and only exchange the loaded view content on a route change. This does not stop your already running animation code from continuing to run in the background while you navigate to another view, so that when you return to the animated tab you will create another set of interval timers for your animation, which will result in more executions and thus a visually faster animation.
#Cristy thanks for the advice!
Here is how I manage to solve this..
I put one property in my pixi-parameters.js:
pixiWasLoaded = false;
Then, when I call initiatePixi() function, I set:
pixiWasLoaded = true;
Now in my controllers.js I have this piece of code:
.run( function($rootScope, $location, $window) {
$rootScope.$watch(function() {
return $location.path();
},
function(page){
if(page == "/hr/reference" || page == "/en/references"){
if($window.pixiWasLoaded)
$window.addRendererElementToDOM();
else
loadReferences();
}
});
});
It checks if references page is loaded and then uses $window to find my global variable "pixiWasLoaded" and if it's not loaded then it loads PixiJS using loadReferences() function.. and if is already loaded it calls my part of code to add render-view to DOM so my animate function can render it..
:: cheers ::
Josip

SVG Camera Pan - Translate keeps resetting to 0 evertime?

Well i have this SVG canvas element, i've got to the point so far that once a user clicks and drags the canvas is moved about and off-screen elements become on screen etc....
However i have this is issue in which when ever the user then goes and click and drags again then the translate co-ords reset to 0, which makes the canvas jump back to 0,0.
Here is the code that i've Got for those of you whio don't wanna use JS fiddle
Here is the JSfiddle demo - https://jsfiddle.net/2cu2jvbp/2/
edit: Got the solution - here is a JSfiddle DEMO https://jsfiddle.net/hsqnzh5w/
Any and all sugesstion will really help.
var states = '', stateOrigin;
var root = document.getElementById("svgCanvas");
var viewport = root.getElementById("viewport");
var storeCo =[];
function setAttributes(element, attribute)
{
for(var n in attribute) //rool through all attributes that have been created.
{
element.setAttributeNS(null, n, attribute[n]);
}
}
function setupEventHandlers() //self explanatory;
{
setAttributes(root, {
"onmousedown": "mouseDown(evt)", //do function
"onmouseup": "mouseUp(evt)",
"onmousemove": "mouseMove(evt)",
});
}
setupEventHandlers();
function setTranslate(element, x,y,scale) {
var m = "translate(" + x + "," + y+")"+ "scale"+"("+scale+")";
element.setAttribute("transform", m);
}
function getMousePoint(evt) { //this creates an SVG point object with the co-ords of where the mouse has been clicked.
var points = root.createSVGPoint();
points.x = evt.clientX;
points.Y = evt.clientY;
return points;
}
function mouseDown(evt)
{
var value;
if(evt.target == root || viewport)
{
states = "pan";
stateOrigin = getMousePoint(evt);
console.log(value);
}
}
function mouseMove(evt)
{
var pointsLive = getMousePoint(evt);
if(states == "pan")
{
setTranslate(viewport,pointsLive.x - stateOrigin.x, pointsLive.Y - stateOrigin.Y, 1.0); //is this re-intializing every turn?
storeCo[0] = pointsLive.x - stateOrigin.x
storeCo[1] = pointsLive.Y - stateOrigin.Y;
}
else if(states == "store")
{
setTranslate(viewport,storeCo[0],storeCo[1],1); // store the co-ords!!!
stateOrigin = pointsLive; //replaces the old stateOrigin with the new state
states = "stop";
}
}
function mouseUp(evt)
{
if(states == "pan")
{
states = "store";
if(states == "stop")
{
states ='';
}
}
}
In your mousedown function, you are not accounting for the fact that the element might already have a transform and you are just overwriting it.
You are going to need to either look for, and parse, any existing transform. Or an easier approach would be to keep a record of the old x and y offsets and when a new mousedown happens add them to the new offset.

Creating an javascript graph with marker that is synchronize with a movie

I'm trying to create an online web tool for eeg signal analysis. The tool suppose to display a graph of an eeg signal synchronize with a movie that was display to a subject.
I've already implemented it successfully on csharp but I can't find a way to do it easily with any of the know javascript chart that I saw.
A link of a good tool that do something similar can be found here:
http://www.mesta-automation.com/real-time-line-charts-with-wpf-and-dynamic-data-display/
I've tried using dygraph, and google chart. I know that it should be relatively easy to create an background thread on the server that examine the movie state every ~50ms. What I was not able to do is to create a marker of the movie position on the chart itself dynamically. I was able to draw on the dygraph but was not able to change the marker location.
just for clarification, I need to draw a vertical line as a marker.
I'm in great suffering. Please help :)
Thanks to Danvk I figure out how to do it.
Below is a jsfiddler links that demonstrate such a solution.
http://jsfiddle.net/ng9vy8mb/10/embedded/result/
below is the javascript code that do the task. It changes the location of the marker in synchronizing with the video.
There are still several improvement that can be done.
Currently, if the user had zoomed in the graph and then click on it, the zoom will be reset.
there is no support for you tube movies
I hope that soon I can post a more complete solution that will also enable user to upload the graph data and video from their computer
;
var dc;
var g;
var v;
var my_graph;
var my_area;
var current_time = 0;
//when the document is done loading, intialie the video events listeners
$(document).ready(function () {
v = document.getElementsByTagName('video')[0];
v.onseeking = function () {
current_time = v.currentTime * 1000;
draw_marker();
};
v.oncanplay = function () {
CreateGraph();
};
v.addEventListener('timeupdate', function (event) {
var t = document.getElementById('time');
t.innerHTML = v.currentTime;
g.updateOptions({
isZoomedIgnoreProgrammaticZoom: true
});
current_time = v.currentTime * 1000;
}, false);
});
function change_movie_position(e, x, points) {
v.currentTime = x / 1000;
}
function draw_marker() {
dc.fillStyle = "rgba(255, 0, 0, 0.5)";
var left = my_graph.toDomCoords(current_time, 0)[0] - 2;
var right = my_graph.toDomCoords(current_time + 2, 0)[0] + 2;
dc.fillRect(left, my_area.y, right - left, my_area.h);
};
//data creation
function CreateGraph() {
number_of_samples = v.duration * 1000;
// A basic sinusoidal data series.
var data = [];
for (var i = 0; i < number_of_samples; i++) {
var base = 10 * Math.sin(i / 90.0);
data.push([i, base, base + Math.sin(i / 2.0)]);
}
// Shift one portion out of line.
var highlight_start = 450;
var highlight_end = 500;
for (var i = highlight_start; i <= highlight_end; i++) {
data[i][2] += 5.0;
}
g = new Dygraph(
document.getElementById("div_g"),
data, {
labels: ['X', 'Est.', 'Actual'],
animatedZooms: true,
underlayCallback: function (canvas, area, g) {
dc = canvas;
my_area = area;
my_graph = g;
bottom_left = g.toDomCoords(0, 0);
top_right = g.toDomCoords(highlight_end, +20);
draw_marker();
}
});
g.updateOptions({
clickCallback: change_movie_position
}, true);
}

Re-size circle using paperJS

I am trying to re-size a circle using papeJS but since i used two onMouseDrag function it if conflicting. I am unable to create it. Can anyone help me. Here is the fiddle with circle
Here is the code.
<script type="text/paperscript" canvas="canvas">
var raster = new Raster({
source: 'Chrysanthemum.jpg',
position: view.center
});
var path = null;
var circles = [];
var isDrawing = false;
var draggingIndex = -1;
var segment, movePath;
var resize = false;
project.activeLayer.selected = false;
function onMouseDrag(event) {
if (!isDrawing && circles.length > 0) {
for (var ix = 0; ix < circles.length; ix++) {
if (circles[ix].contains(event.point)) {
draggingIndex = ix;
break;
}
}
}
if (draggingIndex > -1) {
circles[draggingIndex].position = event.point;
} else {
path = new Path.Circle({
center: event.point,
radius: (event.downPoint - event.point).length,
fillColor: null,
strokeColor: 'black',
strokeWidth: 10
});
path.removeOnDrag();
isDrawing = true;
}
}
;
function onMouseUp(event) {
if (isDrawing) {
circles.push(path);
}
isDrawing = false;
draggingIndex = -1;
}
;
function onMouseMove(event) {
project.activeLayer.selected = false;
if (event.item)
event.item.selected = true;
resize = true;
}
var segment, path;
var movePath = false;
function onMouseDown(event) {
segment = path = null;
var hitResult = project.hitTest(event.point, hitOptions);
if (!hitResult)
return;
if (hitResult) {
path = hitResult.item;
if (hitResult.type == 'segment') {
segment = hitResult.segment;
} else if (hitResult.type == 'stroke') {
var location = hitResult.location;
segment = path.insert(location.index + 1, event.point);
path.smooth();
}
}
movePath = hitResult.type == 'fill';
if (movePath)
project.activeLayer.addChild(hitResult.item);
}
</script>
First, your code (on jsfiddle) does not run.
The paperjs external resource returned a 404. https://raw.github.com/paperjs/paper.js/master/dist/paper.js works for paperjs.
The raster source was for a local file, not a URI.
In onMouseDown, project.hitTest references an undefined hitOptions.
It seems from your question that you want to be able to drag the circle segments to resize the circle, and you tried using two onMouseDrag functions to do that, which would not work. Instead, both operations should be in the same onMouseDrag, using if-then-else to choose between them. To make this work as expected, the item that was hit should be stored in onMouseDown instead of whatever circle your code finds at the beginning of onMouseDrag. For example, here onMouseDrag can either "move" or "resize" (jsfiddle here):
<script type="text/paperscript" canvas="myCanvas">
var raster = new Raster({
source: 'http://i140.photobucket.com/albums/r10/Array39/Chrysanthemum.jpg',
position: view.center
});
var circles = [];
var hitItem = null;
var currentAction = null;
function onMouseMove(event) {
project.activeLayer.selected = false;
if (event.item) {
event.item.selected = true;
}
}
function onMouseDown(event) {
hitItem = null;
var aColor = new Color('black');
for (var i = 0; i < circles.length; i++) {
circles[i].fillColor = aColor;
}
view.draw();
var hitResult = project.hitTest(event.point);
for (var i = 0; i < circles.length; i++) {
circles[i].fillColor = null;
}
view.draw();
if (!hitResult) {
return; //only happens if we don't even hit the raster
}
hitItem = hitResult.item;
if (circles.indexOf(hitItem) < 0) {
var newCircle = new Path.Circle({
center: event.point,
radius: 2,
strokeColor: 'black',
strokeWidth: 10
});
hitItem = newCircle;
circles.push(hitItem);
currentAction = 'resize';
return;
}
if (hitResult.type == 'segment') {
currentAction = 'resize';
} else if (hitResult.type == 'stroke') {
hitItem.insert(hitResult.location.index + 1, event.point);
hitItem.smooth();
currentAction = 'resize';
} else if (hitResult.type == 'fill') {
currentAction = 'move';
}
}
function onMouseDrag(event) {
if (!hitItem) {
return;
}
if (currentAction == 'move') {
hitItem.position = event.point;
} else if (currentAction == 'resize') {
if ((event.downPoint - event.point).length >= 1) {
hitItem.fitBounds(new Rectangle(event.downPoint, event.point), true);
}
}
};
</script>
<canvas id="myCanvas"></canvas>
Also note:
In onMouseDown, the function returns if !hitResult, so you do not need to test if (hitResult) right after that return.
Naming variables the same as objects makes searching more difficult, e.g., in your code path is an instance of Path.
Using the same variable for different purposes makes code more difficult to parse, e.g., in your code path is used to create new circles as well as to store which circle has been selected.
You have multiple variables defined twice: path, movePath, and segment.
If a variable will only be used in a single function, e.g., movePath and segment, then it makes the code more readable if the variable is defined in that function. Also, movePath is only used in a single if-statement, which just adds items back to the layer, but the only items not in the layer have been removed when the circle was originally drawn. Since those items cannot be hit, the item that was hit must already be in the layer.
The variable segment is not used.
It makes the code flow/read better if the functions are ordered logically. In this case, onMouseMove should go first because it happens before the button is clicked. Then onMouseDown goes next because it must happen before the other actions. Then onMouseDrag, and finally onMouseUp.
Instead of creating new circles in onMouseDrag and then throwing them away on the next drag, it makes more sense to create one in onMouseDown if there was no item hit, or if the hit item is not a circle. Then in onMouseDown, you just resize that circle. Path.scale or Path.fitBounds can be used for such resizing.
Instead of using multiple boolean variables to keep track of the current action (e.g., resize vs move), it is more logical to have a single variable keeping track of the current action.
Instead of your code to find whether the point is within a circle, the code I am using temporarily sets the circles' fillColor, do the hitTest, and then clears the circles' fillColor. I did this because when you hit a stroke, the shape of the circle changes, for which your code to find the draggingIndex does not account.

Categories

Resources