Createjs. Line follow element fiddle - createjs

I created this jsfiddle.
A line i connecting two elements, and I want the line to stay connected to both elements no matter where they go.
I've sort of succeeded, but with one pretty obvious error. It keeps drawing new lines instead of redrawing the existing line. Please help me on how to make it update the line position instead.
var stage = new createjs.Stage("canvas");
createjs.Ticker.setFPS(60);
createjs.Ticker.addEventListener("tick", tick);
var arrDots = [];
var arrLines = [];
var circle1 = new createjs.Shape().set({
x: stage.canvas.width/2,
y: 50,
cursor: "pointer",
name:"target"
});
circle1.graphics.f(createjs.Graphics.getRGB(Math.random()*0xFFFFFF))
.dc(0,0,20);
stage.addChild(circle1);
arrDots.push(circle1);
var circle2 = new createjs.Shape().set({
x: stage.canvas.width/2,
y: stage.canvas.height - 50,
cursor: "pointer",
name:"target"
});
circle2.graphics.f(createjs.Graphics.getRGB(Math.random()*0xFFFFFF))
.dc(0,0,20);
stage.addChild(circle2);
arrDots.push(circle2);
var line = new createjs.Shape().set({
graphics: new createjs.Graphics().s("#00f").mt(arrDots[0].x,
arrDots[0].y).lt(arrDots[1].x, arrDots[1].y)
});
stage.addChild(line);
arrLines.push([arrDots[0], arrDots[1], line]);
createjs.Tween.get(circle1, {loop: true}).to({x:50},
3000).to({x:stage.canvas.width/2}, 3000);
function tick(event) {
keepLineConnection();
stage.update();
}
function keepLineConnection() {
for(var i = 0; i < arrLines.length; i++) {
arrLines[i][2].graphics.mt(arrLines[i][0].x, arrLines[i][0].y).lt(arrLines[i][1].x, arrLines[i][1].y);
}
}

The reason it keeps drawing is because you keep adding commmands to the graphics. Basically, you are doing this:
graphics.mt().lt().mt().lt().mt().lt().mt().etc();
Since you are just adding new instrucitons, they will pile up over time,
and will eventually kill your processor.
An easy fix for that is to clear the graphics first before adding new ones:
graphics.clear().mt().lt();
A better approach is to use commands. Since EaselJS 0.7.0, all graphics commands are objects, and at any time you can update properties of those objects directly. For example, the MoveTo and LineTo commands both have an x and y property. Here is more info on Commands: http://blog.createjs.com/update-width-height-in-easeljs/
Here is a modified fiddle that stores of commands on the line, and then updates them on tick. I also made a few other updates, such as changing the timing mode to RAF, which is smoother than using interval-based timers at 60FPS.
https://jsfiddle.net/tck7x8u2/
// Store commands:
line.cmd1 = line.graphics.mt(0,0).command;
line.cmd2 = line.graphics.lt(0,0).command;
// Update commands:
var instr = arrLines[i],
line = instr[2];
line.cmd1.x = instr[0].x;
line.cmd1.y = instr[0].y;
line.cmd2.x = instr[1].x;
line.cmd2.y = instr[1].y;
Cheers!
Edit: Here is are some demos using that idea that I made a while back:
https://lab.gskinner.com/connections
http://jsfiddle.net/lannymcnie/2xoL08bx/
http://jsfiddle.net/lannymcnie/6rh7P/

Related

how do i make an objects continuously spawn on kaboom.js

When I shoot the asteriod they disapear which is what i want however I want more asteriods to spawn instead of them just disapearing forever.Im not sure what to add in this code to make more spawn into the game.
any help is appreciated
i thought making the number of asteriods a constant would make sure that 5 asteriods are on screen at all times however that didnt seem to work
// the asteroids
const NUM_ASTERIODS = 3;
for (let i = 0; i < NUM_ASTERIODS; i++) {
var spawnPoint = asteroidSpawnPoint();
var a = add([
sprite("asteroid"),
pos(spawnPoint),
rotate(rand(1,90)),
origin("center"),
area(),
scale(0.2),
solid(),
"asteroid",
"mobile",
"wraps",
{
speed: rand(5, 10),
initializing: true
}
]);
while (a.isColliding("mobile")) {
spawnPoint = asteroidSpawnPoint();
a.pos = spawnPoint;
a.pushOutAll();
}
a.initializing = false;
a.pushOutAll();
}
function asteroidSpawnPoint() {
// spawn randomly at the edge of the scene
return choose([rand(vec2(0), vec2(width(), 0)),
rand(vec2(0), vec2(0, height())),
rand(vec2(0, height()), vec2(width(), height())),
rand(vec2(width(), 0), vec2(width(), height()))]);
}
I had a similar problem when trying to spawn continuous sprites from the top of the screen. I found the following code worked to spawn my sprites at random positions (x-axis) across the top of the screen (y-axis).
Kaboom suggests using the wait() method within a recursive function in their tutorial, which avoids using a loop and allows you to control the frequency of spawning.
function spawnAsteroid() {
add([sprite('asteroid'),
pos(rand(width()), 0),
origin(),
body(),
'dangerous'
])
wait(rand(0.5, 1), spawnAsteroid);
}
spawnAsteroid();

Cannonjs move body forward according to its quaternion

I'm struggling with Cannonjs physics lib, I got a sphere body with a changing quaternion, I just want that body to move forward according to its quaternion. I found many topics related to that but none of the suggested codes is working.
Is it a simple way to achieve that simple task?
So far I tried the solution given here but the using of vmult() method do not change the vector3 at all...
body.quaternion = new CANNON.Quaternion(0,1,0,0); // Whatever value you put here will not change the result of the vmult() operation below
var localVelocity = new CANNON.Vec3(0, 0, 1);
var worldVelocity = body.quaternion.vmult(localVelocity); //-> worldVelocity = (0,0,1)
body.velocity.copy(worldVelocity);
Try to set and not copy the body.velocity, this way:
let directionVector = new CANNON.Vec3(0, 0, 1);
directionVector.z -= moveDistance;
directionVector = vehicleBody.quaternion.vmult( directionVector );
vehicleBody.velocity.set( directionVector.x, directionVector.y, directionVector.z );

AmCharts 4 : Can't customize (color, strokeWidth) my series

EDIT : OK, It was my css page which had a rule on path, 'cause I use svg a lot. Removed that rule and the problem was gone !
I'm facing something pretty annoying and which I do not understand.
I'm using amChart to make a XY chart with multiple series. Not that hard.
The thing is, I can't customize my series ! Bullets and legend are ok, but not series.
Here's a screenshot for better understanding :
MyWeirdChart (new OP can't embed images, sorry)
As you can see I have my custom bullet pushed on my series and my legend is exactly what I want for my chart BUT series are staying unchanged.
Here is my JS draw function :
function drawChart(dateArray, casesArray, deathsArray, healedArray, hospitalizationsArray, reanimationsArray) {
am4core.useTheme(am4themes_animated);
var chart = am4core.create("chartdiv", am4charts.XYChart);
chart.data = generateChartData(dateArray, casesArray, deathsArray, healedArray, hospitalizationsArray, reanimationsArray);
var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
function pushSeries(field, name, color) {
let series = chart.series.push(new am4charts.LineSeries());
series.dataFields.valueY = field;
series.dataFields.dateX = "date";
series.name = name;
series.tooltipText = name + ": [b]{valueY}[/]";
series.stroke = am4core.color(color);
series.strokeWidth = 3;
series.fill = am4core.color(color);
series.fillOpacity = 0.5;
let bullet = series.bullets.push(new am4charts.CircleBullet());
bullet.circle.stroke = am4core.color(color);
bullet.circle.strokeWidth = 2;
bullet.circle.fill = am4core.color(color);
bullet.circle.fillOpacity = 0.5;
bullet.circle.radius = 3;
}
pushSeries("cases", "Cas confirmés", "#32B3E3");
pushSeries("healed", "Guéris", "#00C750");
pushSeries("hospitalizations", "Hospitalisations", "#FFBB33");
pushSeries("reanimations", "Réanimations", "#FE3446");
pushSeries("deaths", "Morts", "black");
chart.cursor = new am4charts.XYCursor();
chart.scrollbarX = new am4core.Scrollbar();
chart.legend = new am4charts.Legend();
chart.cursor.maxTooltipDistance = 0;
}
Did I miss something ? I crawled forums and documentations and I'm now helpless.
My code is in my webpack app.js file. But I include amCharts with HTML scripts,
<script src="https://www.amcharts.com/lib/4/core.js"></script>
<script src="https://www.amcharts.com/lib/4/charts.js"></script>
<script src="https://www.amcharts.com/lib/4/themes/animated.js"></script>
not with webpack import. But I guess that if this was the problem, I would not be able to draw a chart at all.
OK, It was my css page which had a rule on path, 'cause I use svg a lot. Removed that rule and the problem was gone !

Is there a better way to fix my AS2 preloader?

I have a game with a preloader in scene 1, with the following code on the time line.
stop();
loadingBar._xscale = 1;
var loadingCall:Number = setInterval(preloadSite, 50);
function preloadSite():Void {
var siteLoaded:Number = _root.getBytesLoaded();
var siteTotal:Number = _root.getBytesTotal();
var percentage:Number = Math.round(siteLoaded/siteTotal*100);
loadingBar._xscale = percentage;
bytesDisplay.text = percentage + "%";
if (siteLoaded >= siteTotal) {
clearInterval(loadingCall);
gotoAndPlay("StartMenu", 1);
}
}
The code works fine when there are no music files linked to frame 1. If there are music files linked, then everything loads before the preloader shows up.
I found this great webpage about preloaders, which speaks about the linkage issue, and suggests I put all the big files on frame 2, after the preloader, then skip them. I put my large files on frame 2 as suggested and the preloader worked again.
My question is, is there a better way to do this. This solution seems like a hack.
The only better option I can think of, is to NOT store the MP3 file in your Flash file, but rather load it in your preloader with your flash file's content. This is provided that you're storing your MP3 file somewhere else online (like on a server).
stop();
loadingBar._xscale = 1;
var sound:Sound = new Sound();
sound.loadSound("http://www.example.com/sound.mp3", false);
var loadingCall:Number = setInterval(preloadSite, 50);
function preloadSite():Void {
var siteLoaded:Number = _root.getBytesLoaded()+sound.getBytesLoaded();
var siteTotal:Number = _root.getBytesTotal()+sound.getBytesTotal();
var percentage:Number = Math.round(siteLoaded / siteTotal * 100);
loadingBar._xscale = percentage;
bytesDisplay.text = percentage + "%";
if (siteLoaded >= siteTotal) {
clearInterval(loadingCall);
gotoAndPlay("StartMenu", 1);
sound.start();
}
}

KineticJS won't draw a dashed line in Internet Explorer 10

Trying to display a dashed line with KineticJS (v4.7.3). It works fine in Chrome, but in IE (v10), a normal solid line is displayed.
Here's the code:
var element = document.getElementById('target'),
stage = new Kinetic.Stage({
container: element,
width: element.offsetWidth,
height: element.offsetHeight
}),
layer = new Kinetic.Layer();
layer.add(new Kinetic.Line({
points: [10, 10, 190, 190],
stroke: 'black',
strokeWidth: 1,
dashArray: [5, 4]
}));
stage.add(layer);
And you can see the behavior for yourself in here.
Fixed in IE-11 !
Until all "bad" IE's die, you can "do-it-yourself" fairly easily for lines (less easily for curves).
You can use a custom Kinetic.Shape which gives you access to a canvas context (a wrapped context).
Code is taken from this SO post: dotted stroke in <canvas>
var CP = window.CanvasRenderingContext2D && CanvasRenderingContext2D.prototype;
if (CP && CP.lineTo){
CP.dashedLine = function(x,y,x2,y2,dashArray){
if (!dashArray) dashArray=[10,5];
if (dashLength==0) dashLength = 0.001; // Hack for Safari
var dashCount = dashArray.length;
this.moveTo(x, y);
var dx = (x2-x), dy = (y2-y);
var slope = dx ? dy/dx : 1e15;
var distRemaining = Math.sqrt( dx*dx + dy*dy );
var dashIndex=0, draw=true;
while (distRemaining>=0.1){
var dashLength = dashArray[dashIndex++%dashCount];
if (dashLength > distRemaining) dashLength = distRemaining;
var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
if (dx<0) xStep = -xStep;
x += xStep
y += slope*xStep;
this[draw ? 'lineTo' : 'moveTo'](x,y);
distRemaining -= dashLength;
draw = !draw;
}
}
}
Totally off-topic: Go Wisconsin! I spent many a great summer at my grandmothers house in
Lacrosse.
Short answer: Not supported.
Via a thread here, the creator of KineticJS addresses this issue:
"[T]he dashArray property now uses the browser-implemented dashArray
property of the canvas context, according to the w3c spec. Firefox is
a little behind at the moment."
If you follow the thread, you'll discover that this was an issue for Firefox at one point, too, but that has been resolved. However, support for IE should apparently not be expected any time soon.