Label above a body in Phaser - javascript

I have an array with bodies. For each one of them I want to put a label with some info. I've managed to do it, but when I turn them the label turns too.
// Main body
players[id] = game.add.sprite(game.world.randomX, 200, sprite, sprite_ini);
game.physics.p2.enable(players[id]);
players[id].animations.add('walk', [1,2,3,4], 10, true);
players[id].animations.add('stand', [0], 0, true);
players[id].animations.add('jump', [5], 0, true);
// Add weapon
bazuca = game.add.sprite(0, 0, 'bazuca');
players[id].addChild(bazuca);
// Labels
players[id].body.label_nome = game.add.text(
-35,
-55,
"Info",
{ font: "bold 14px Arial", fill: color});
players[id].addChild(players[id].body.label_nome);
And they are turned with
players[id].scale.x = -1;
The animation turns and works perfectly, the weapon also turns and stays in place, but the label also turns. How can I avoid that? The label should move with the body, but not turn.

I see two solutions:
Kamen Minkov's one, i.e. keeping the labels out of the groups and update their position on each frame (there doesn't seem to be an "onMove" signal or something).
Since you're using P2, you could actually physics-enable the labels, set "body.fixedRotation = true" on them, and create a constraint between each label and each sprite to make thhe labels follow the sprites.
The second solution seems more elegant and maintainable but performance-wise the first one is probably better.

If you set the label to be the same x value as the item it is labeling, and the y value of the label to be less than that of the object. Here is example code:
//in create():
label.anchor.setTo(.5, .5); /*sets positioning to center.
You need to make sure that arcade physics are applied to label*/
//in update():
label.x = object.x;
label.y = object.y - 60;
//change the 60 to whatever looks good to you when running.
To apply arcade physics:
//in create():
game.physics.startSystem(Phaser.Physics.ARCADE); // do this once
game.physics.enable(label/*change this to what you want the physics to apply to*/, Phaser.Physics.ARCADE);
Hope this helps.

Related

How to stop- Transform rotate - animation while it detects and specific value added into an array

Good day. I'm having some troubles with style transform rotate. Actually it's not a problem bcs it's working correctly. The point is I'm trying to make a "fortune wheel", this one activates it's rotate animation if I press a button.
This button have some funciontionalities. It adds the information texted in a textarea to and array, after that, creates the wheel depending of the qty of items in the array and then proceed the rotation. Trying to find a solution, I added an IF conditional, this one makes the wheel stop if it reaches some degrees of rotation.
But that is not what I want. I need to make the wheel stops at the moment it detects an specific value in my array. I don't if it's clear enough, to me this sounds very complicated and don't have the enough level to find a way to make it works, haha. This is my function code:
function sort(){
names= document.getElementById("names").value;
names= names.split(",");
names= names.reverse();
console.log(names);
//wheel border
context.beginPath();
context.moveTo(center,center);
context.arc(center,center,center-10,0,2*Math.PI);
context.lineTo(center, center);
context.fillStyle="black";
context.fill();
for (let i = 0; i < names.length; i++){
context.beginPath();
context.moveTo(center,center);
context.arc(
center,center,
center-20,
i*2*Math.PI/names.length,
(i+1)*2*Math.PI/names.length);
context.lineTo(center, center);
context.fillStyle=random_color();
context.fill();
//Names added in the circle
context.save();
context.translate(center,center);
context.rotate(3*2*Math.PI/(5*names.length)+i*2*Math.PI/names.length);
context.translate(-center, -center);
context.font="30px Sans Serif";
context.textAlign="right";
context.fillStyle="white";
context.fillText(names[i], canvas.width-30,center);
context.restore();
}
//I think this is the part that needs the "**SPECIAL**" modification
if(click == 0){
let canvas = document.getElementById("idCanvas");
movement=setInterval(function(){
posInicial+=50;
canvas.style.transform= 'rotate('+posInicial+'deg)';
//Automatucally pauses at the moment it reaches the number
if(posInicial > 10000){
clearInterval(movement)
posInicial = 0;
}
},10);
click=1;
document.getElementById("idStatus")=="Stop";
}else{
clearInterval(movement);
click=0;
document.getElementById("idStatus")=="Sort";
}
}

pts.js: Speed up animation of grid cells?

I'm using Pts.js to create a grid of cells and then color these cells depending on their distance to the mouse pointer. My code is largely based on a demo from the official Pts.js Website.
Pts.quickStart("#pt", "#123");
//
let pts = [];
var follower = new Pt();
space.add({
start: (bound) => {
pts = Create.gridCells(space.innerBound, 40, 20);
follower = space.center;
},
//
animate: (time, ftime) => {
follower = follower.add(space.pointer.$subtract(follower).divide(20));
form.stroke("#123");
//
let rects = pts.map((p) => {
let color;
let mag = follower.$subtract(Rectangle.center(p)).magnitude();
let r = Rectangle.fromCenter(Rectangle.center(p), Rectangle.size(p));
//
if (mag >= 100) {
color = "#000"
} else {
color = "#f00"
}
//
form.fill(color).rect(r);
})
//
form.fillOnly("#fff").point(space.pointer, 10, "circle");
}
})
//
space.bindMouse().bindTouch().play();
#pt {
width: 800px;
height: 600px;
margin: 30px auto 0;
}
<script src="https://unpkg.com/pts#0.9.4/dist/pts.min.js"></script>
<div id="pt"></div>
The implementation works absolutely fine. But I'd like to increase the speed with which the »coloring« of the cells »follows« the cursor, i.e. reduce the delay with which the red space around the cursor is animated. Ideally, I'd like to have no delay.
I'm new to Pts.js, so still wrapping my head around the docs, and I can't find an option or explanation for how to control the animation's speed. If anyone could point me to what I need to do here, that'd be great.
It seems that this line is what controls the behavior of the red grid area:
follower = follower.add(space.pointer.$subtract(follower).divide(20));
The value supplied to .divide() controls the speed at which the red area follows the cursor. Changing its argument from 20 to 1 (or even removing .divide(20) entirely) causes the "following" behavior to be immediate.
(Though, if you intend to remove the capability for that behavior, I suspect that entire line could be simplified.)

How to give a single line serie multiple colors with Tradingview Lightweight charts in Javascript?

This image below is what I have at this moment.
This image below is what I want. (1st image from my code, second from tradingview).
To be clear: I want a single line to have multiple colors. For my situation I need only two colors. I need each new line I create changable in color. Its a nice to have if the price tag on the right also changes to the color of the line that hits the right part of the chart.
This is my code:
var chart = LightweightCharts.createChart(document.getElementById("Chart"), {width: 1500, height: 700});
/**
* Creates startline and adds extra options to the lineSeries.
*/
function initChartSettings() {
// Init lines
priceArea = chart.addAreaSeries();
buySellLine = chart.addLineSeries(); //LINE THAT NEEDS TWO COLORS
// Set start position of lines
priceArea.setData([{time: '2019-04-11', value: startPrice}]);
buySellLine.setData([{time: '2019-04-11', value: startPrice}]);
// Visualization edits
priceArea.applyOptions({
topColor: 'rgba(70, 130, 180, 0.5)',
bottomColor: 'rgba(70, 130, 180, 0.1)',
lineColor: '#4682B4'
});
// Buy sell line
buySellLine.applyOptions({
color: '#42f54b', //CHANGES COLOR OF THE COMPLETE LINE, FROM BEGIN TO END.
priceLineVisible: true,
lastValueVisible: true
});
updateChartStatic();
}
/**
* Updates the chart its lines.
*/
function updateChartStatic() {
setTimeout(() => {
priceArea.update({
time: yearMonthDay, //How this works should not matter for question
value: newPrice, //Same as above
});
// Updates the price line of the chart.
buySellLine.update({
time: yearMonthDay,
value: currentMovingAverage //Even though it would be nice to do the below commented thing...
// color: 'red or green (example)'
});
buySellLine.applyOptions({
color: changeLineColor(currentMovingAverage, lastMovingAverage) // CHANGES COMPLETE LINE :(
});
}, 1);
}
the changeLineColor() function is doing an if statement, which has nothing to do with setting a color to a line.
EDIT: As this feature was landed in v3.8 you can simply add color properties to any of your data items by using the following properties in the data:
LineData.color to change a color of line data item
CandlestickData.color to change a body color of a candlestick item
CandlestickData.borderColor to change a border color of a candlestick item
CandlestickData.wickColor to change a wick color of a candlestick item
Note that you don't need to provide all the colors and you can provide only necessary ones (e.g. only body color for some candlestick items).
Original answer:
It's impossible right now, but there is issue for this feature https://github.com/tradingview/lightweight-charts/issues/195. You can subscribe on it to being notified when it'll be fixed (or even make a proposal and/or provide a PR with changed).

Set ECG paper-like grid intervals (highcharts.js)

I need to show an ECG result with highcharts which is basically a simple line/spline diagram but with a little tweak. The ECG paper looks like this: https://cdn.printablepaper.net/samples/ECG_Paper.png
And this is what I want to achieve with hightcharts too. One little square means 0.1 mV and 0.04 s, so one big square is 0.5 mV and 0.2 s. I know there is a tickInterval setting, but that just does not work in this scenario, I think the intervals are too small for it, because it randomly hides grid lines.
The optimal solution would be that if there is a need for hiding grid lines (too broad data), it only hides the small squares. To try not to confuse the users with this, we also would like to colorize grid lines differently, so every fifth line should be red, others gray.
Is this possible with highcharts?
minorTicks functionality seems to be ideal for this case. Use this option along with minorTickInterval. Configuration for both axes will look like this:
var axesOptions = {
tickInterval: 0.5,
minorTicks: true,
minorTickInterval: 0.1,
gridLineWidth: 1,
gridLineColor: 'red'
};
Live demo: http://jsfiddle.net/kkulig/6dbnmyxf/
If minor ticks are not visible on any axis this code will hide them on all axes (and restore them when needed):
chart: {
events: {
render: function() {
var axes = this.axes,
showMinorTicks = true;
// find if minor ticks are present on both axes
axes.forEach(function(a) {
console.log(a.minorTicks);
if (Object.keys(a.minorTicks).length === 0) {
showMinorTicks = false;
}
});
// hide/show ticks
axes.forEach(function(a) {
for (var key in a.minorTicks) {
var mt = a.minorTicks[key].gridLine;
showMinorTicks ? mt.show() : mt.hide();
}
});
}
}
},
API references:
https://api.highcharts.com/highcharts/xAxis.minorTickInterval
https://api.highcharts.com/highcharts/xAxis.minorTicks

how to change size of raphael icons?

how I can change the width and the height of icons from free Raphael icons ?
I tried to use attr, tried to use % , like this var paper = Raphael("canvas", 100%, 100%);.
I need to do this: if I change the size of the parent block, the size of my icon changes too.
upd: i tried use "scale" and "transform", but icon resize from centre and not fit into the parent correctly
According to the Raphael.js documentation
var el = paper.rect(10, 20, 300, 200);
// translate 100, 100, rotate 45°, translate -100, 0
el.transform("t100,100r45t-100,0");
// if you want you can append or prepend transformations
el.transform("...t50,50");
el.transform("s2...");
// or even wrap
el.transform("t50,50...t-50-50");
// to reset transformation call method with empty string
el.transform("");
// to get current value call it without parameters
console.log(el.transform());
Check this Fiddle:
Demonstration of all the transformations
var icon = paper.rect(100,200,100,100);
var anim = Raphael.animation({
"10%":{transform:'t100,0'}, //transform on x-axis
"20%":{transform:'...t0,100'},//transform on y-axis
"30%":{transform:'...t-100,0'},//transform on x-axis(negative)
"40%":{transform:'...t0,-100'},//transform on y-axis(negative)
"50%":{transform:'...t200,200'},//transform diagonally
"60%":{transform:'...t-100,-100'},//transform diagonally(negative)
"70%":{transform:'...s1,1.5'},//scale y-axis
"80%":{transform:'...s1.5,1'},//scale x-axis
"90%":{transform:'...s2'},//scale in both direction
"100%":{transform:'...r45'},//rotate
},5000);
icon.animate(anim.delay(1000));
So in your case you'll have to do this:
var somename = paper.path("path coordinates").transform('s2,3');
where 2 is for width & 3 is for height.

Categories