Bouncing a body from the walls of another body. Phaser3 - phaser-framework

var config = {
type: Phaser.AUTO,
width: 800,
height: 600,
backgroundColor: '#1b1464',
parent: 'phaser-example',
physics: {
default: 'matter',
matter: {
debug: true
}
},
scene: {
preload: preload,
create: create
}
};
var game = new Phaser.Game(config);
function preload ()
{
this.load.image('red', 'assets/sprites/columns-red.png');
}
function create ()
{
this.matter.world.setBounds(100, 0, 600, 400, 1).disableGravity();
console.log(this.matter.world.walls.bottom)
var circ = this.matter.add.image(200, 50, 'red');
// Change the body to a Circle with a radius of 48px
circ.setBody({
type: 'circle',
radius: 48
});
// Just make the body move around and bounce
circ.setVelocity(6, 3);
circ.setAngularVelocity(0.01);
circ.setBounce(1);
circ.setFriction(1, 0, 0);
}
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="//cdn.jsdelivr.net/npm/phaser#3.19.0/dist/phaser.js"></script>
<script src="//cdn.jsdelivr.net/npm/phaser#3.19.0/dist/phaser.min.js"></script>
</head>
There is a code according to which the ball is squared and bounces off its walls. How can I rotate this square?
I am ready to accept proposals for the implementation of this example on other phaser engines

Related

Chart.js - Dynamic Data sources based on new data point entry in JSON File

can someone support me here. Im using Chart.js libary to show in realtime beacon data from backend by using an websocket client technology.
The data are sent to frontend via websocket and in a "JSON format". Every 5 Seconds a new single is sent (see picture).
My Question is can I add a new data source dynamically including a data source label on the header with the Beacon ID to filter the rssi value by beaconID in case that a new beacon-ID would be sent from the backend?
Markus
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdn.socket.io/4.5.3/socket.io.min.js"
integrity="sha384-WPFUvHkB1aHA5TDSZi6xtDgkF0wXJcIIxXhC6h8OT8EH3fC5PWro5pWJ1THjcfEi"
crossorigin="anonymous"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.3.2"></script>
<script src="https://cdn.jsdelivr.net/npm/luxon#^2"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon#^1"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-streaming#2.0.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2 "></script>
<title>Demo Plugin Streaming in Chart.js</title>
<style type="text/css">
.chartBox {
width: 600px;
}
</style>
</head>
<body>
<div class="chartBox">
<canvas id="myChart"></canvas>
</div>
<button onclick="pauseChart()">Pause Chart</button>
<script>
//setblock
const data = {
labels: [],
datasets: [{
label: [],
data: [],
backgroundColor: 'rgba(75, 192, 192, 0.2)',
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1
},
{
label: [],
data: [],
backgroundColor: 'rgba(ß, 0, 192, 0.2)',
borderColor: 'rgba(0, 0, 192, 1)',
borderWidth: 1
}
]
};
//config block
const config = {
type: 'line',
data,
options: {
plugins: {
streaming: {
duration: 40000,
ttl: 60000,
refresh: 1000,
frameRate: 1,
pause: false
}
},
interaction: {
intersect: false
},
scales: {
x: {
type: 'realtime',
realtime: {
// delay: 2000,
onRefresh: chart => {
}
}
},
y: {
min: -100,
max: 0,
},
},
},
};
// render init block
const myChart = new Chart(
document.getElementById('myChart'),
config
);
function pauseChart() {
if (myChart.options.plugins.streaming.pause === false) {
myChart.options.plugins.streaming.pause = true;
} else {
myChart.options.plugins.streaming.pause = false;
}
myChart.update({ delay: 0 });
};
// Listen for messages
const socket = io("http://localhost:3000");
// client-side
socket.on("JSON_Data", function (message) {
const obj = JSON.parse(message);
const dataArray = Object.values(obj);
index = dataArray[0] - 1;
addData(myChart, dataArray[0].beaconMac, dataArray[0].rssi);
});
function addData(chart, label, data) {
chart.data.labels = label
console.log(label);
console.log(data);
chart.data.datasets.forEach((dataset) => {
dataset.data.push({
x: Date.now(),
y: data,
});
});
chart.update({ delay: 0 });
}
</script>
</body>
</html>
I tried to use the "dynamicy plugin streaming" libary of chart.js and I thought this libary will support dynamically this feature that whenever a field value would change that a new data source is automatically added, but I found nothing in the documenation.
https://nagix.github.io/chartjs-plugin-streaming/master/guide/

Code for a platform moving back and Forth

I'am trying to make a game where the character can jump on a platform that's moving Horizontally, once the platform reaches a specific point it comes back and it repeats. However I have had some trouble finding the correct way to write the code for this I tried using setVelocityX() is looks like this
var movingPlatform = {
moveRight : function(){
platforms.setVelocityX(100)
},
moveleft : function(){
platforms.setVelocityX(-100);
}
}
var move = true;
if(move = true){
movingPlatform.moveRight()
}
if(move = false){
movingPlatform.moveleft();
}
if(platforms.x <= platformMinX){
move = true;
}
if(platforms.x >= platformMaxX){
move = false;
}
all this did was when the platform reaches the 'platformMaxX' point it just moved back and forth in that area so 'movingPlatform.moveRight()' is still being called
var config = {
type: Phaser.AUTO,
parent: 'phaser-example',
width: 800,
height: 600, loader: {
baseURL: 'https://raw.githubusercontent.com/nazimboudeffa/assets/master/',
crossOrigin: 'anonymous'
},
scene: {
preload: preload,
create: create,
update: update
},
physics: {
default: 'arcade'
}
};
var game = new Phaser.Game(config);
var dude;
var alien1, alien2;
var direction = 1
function preload ()
{
this.load.image('dude', 'sprites/phaser-dude.png');
this.load.image('alien1', 'sprites/phaser-alien.png');
this.load.image('alien2', 'sprites/alien2.png');
}
function create ()
{ dude = this.physics.add.sprite(300, 100, 'dude');
alien1 = this.physics.add.sprite(400, 100, 'alien1');
alien1.body.immovable = true;
alien2 = this.physics.add.sprite(100, 100, 'alien2');
alien2.body.immovable = true;
}
function update ()
{
this.physics.add.collider(dude, alien1, flipX, null, this);
this.physics.add.collider(dude, alien2, flipX, null, this);
dude.setVelocityX(direction * 100)
}
function flipX ()
{
direction = - direction
}
<script src="//cdn.jsdelivr.net/npm/phaser#3.18.1/dist/phaser.min.js"></script>
var config = {
type: Phaser.AUTO,
parent: 'phaser-example',
width: 800,
height: 600, loader: {
baseURL: 'https://raw.githubusercontent.com/nazimboudeffa/assets/master/',
crossOrigin: 'anonymous'
},
scene: {
preload: preload,
create: create
},
physics: {
default: 'arcade'
}
};
var game = new Phaser.Game(config);
function preload ()
{
this.load.image('dude', 'sprites/phaser-dude.png');
}
function create ()
{
this.dude = this.physics.add.sprite(100, 100, 'dude');
const tween = this.tweens.add({
targets: this.dude,
x: 300,
ease: 'Power0',
duration: 3000,
flipX: true,
yoyo: true,
repeat: -1,
});
}
<script src="//cdn.jsdelivr.net/npm/phaser#3.19.0/dist/phaser.js"></script>

Phaser 3 - How to create smooth zooming effect

How can I make a zooming effect instead of instant zooming?
Hi there, i'm currently developing a game, which will zoom in when the condition is true. To do that, i followed this link.
https://rexrainbow.github.io/phaser3-rex-notes/docs/site/camera/
camera = this.cameras.main;
if (condition) {
camera.setZoom(3);
camera.zoom = 3;
}
It works, but there's no transition/animation of the zooming. It just simply zoomed.
How can I make a zooming effect instead of instant zooming?
You can play with the pan call and replace 'Power2' by :
Elastic
Sine.easeInOut
Or leave it blank
var config = {
type: Phaser.AUTO,
parent: 'phaser-example',
width: 800,
height: 600, loader: {
baseURL: 'https://raw.githubusercontent.com/nazimboudeffa/assets/master/',
crossOrigin: 'anonymous'
},
scene: {
preload: preload,
create: create
}
};
var game = new Phaser.Game(config);
function preload ()
{
this.load.image('map', 'pics/hyrule.png');
}
function create ()
{
this.cameras.main.setBounds(0, 0, 1024, 1024);
this.add.image(0, 0, 'map').setOrigin(0);
this.cameras.main.setZoom(1);
this.cameras.main.centerOn(0, 0);
this.input.on('pointerdown', function () {
var cam = this.cameras.main;
cam.pan(500, 500, 2000, 'Power2');
cam.zoomTo(4, 3000);
}, this);
}
<script src="//cdn.jsdelivr.net/npm/phaser#3.17.0/dist/phaser.min.js"></script>

Text area in svg shapes

Created a text area in svg using joint js. However, I am not able to enter any text in the text area. How to make the text area editable?
Code:
var graph = new joint.dia.Graph;
var paper = new joint.dia.Paper({
el: $('#myholder'),
width: 1500,
height: 700,
model: graph
});
// Create a custom element.
// ------------------------
joint.shapes.html = {};
joint.shapes.html.Element = joint.shapes.basic.Generic.extend(_.extend({}, joint.shapes.basic.PortsModelInterface, {
markup: '<g class="rotatable"><g class="scalable"><rect/></g><g class="inPorts"/><g class="outPorts"/></g>',
portMarkup: '<g class="port<%=1%>"><circle/></g>',
defaults: joint.util.deepSupplement({
type: 'html.Element',
size: {width: 100, height: 80},
inPorts: [],
outPorts: [],
attrs: {
'.': {magnet: false},
rect: {
stroke: 'none', 'fill-opacity': 0, width: 150, height: 250,
},
circle: {
r: 6, //circle radius
magnet: true,
stroke: 'black'
},
'.inPorts circle': {fill: 'green', magnet: 'passive', type: 'input'},
'.outPorts circle': {fill: 'red', type: 'output'}
}
}, joint.shapes.basic.Generic.prototype.defaults),
getPortAttrs: function (portName, index, total, selector, type) {
var attrs = {};
var portClass = 'port' + index;
var portSelector = selector + '>.' + portClass;
var portCircleSelector = portSelector + '>circle';
attrs[portCircleSelector] = {port: {id: portName || _.uniqueId(type), type: type}};
attrs[portSelector] = {ref: 'rect', 'ref-y': (index + 1) * (10 / total)};
if (selector === '.outPorts') {
attrs[portSelector]['ref-dx'] = 0;
}
return attrs;
}
}));
// Create a custom view for that element that displays an HTML div above it.
// -------------------------------------------------------------------------
joint.shapes.html.ElementView = joint.dia.ElementView.extend({
template: [
'<div class="html-element">',
'<button class="delete">x</button>',
'<span id="lbl" value="Please write here"></span>',
'<textarea id="txt" type="text" value="Please write here"></textarea>',
'</div>'
].join(''),
initialize: function () {
_.bindAll(this, 'updateBox');
joint.dia.ElementView.prototype.initialize.apply(this, arguments);
this.$box = $(_.template(this.template)());
// Prevent paper from handling pointerdown.
this.$box.find('input,select').on('mousedown click', function (evt) {
evt.stopPropagation();
});
// This is an example of reacting on the input change and storing the input data in the cell model.
this.$box.find('textarea').on('change', _.bind(function (evt) {
this.model.set('textarea', $(evt.target).val());
}, this));
this.$box.find('.delete').on('click', _.bind(this.model.remove, this.model));
// Update the box position whenever the underlying model changes.
this.model.on('change', this.updateBox, this);
// Remove the box when the model gets removed from the graph.
this.model.on('remove', this.removeBox, this);
this.updateBox();
this.listenTo(this.model, 'process:ports', this.update);
joint.dia.ElementView.prototype.initialize.apply(this, arguments);
},
render: function () {
joint.dia.ElementView.prototype.render.apply(this, arguments);
this.paper.$el.prepend(this.$box);
// this.paper.$el.mousemove(this.onMouseMove.bind(this)), this.paper.$el.mouseup(this.onMouseUp.bind(this));
this.updateBox();
return this;
},
renderPorts: function () {
var $inPorts = this.$('.inPorts').empty();
var $outPorts = this.$('.outPorts').empty();
var portTemplate = _.template(this.model.portMarkup);
_.each(_.filter(this.model.ports, function (p) {
return p.type === 'in'
}), function (port, index) {
$inPorts.append(V(portTemplate({id: index, port: port})).node);
});
_.each(_.filter(this.model.ports, function (p) {
return p.type === 'out'
}), function (port, index) {
$outPorts.append(V(portTemplate({id: index, port: port})).node);
});
},
update: function () {
// First render ports so that `attrs` can be applied to those newly created DOM elements
// in `ElementView.prototype.update()`.
this.renderPorts();
joint.dia.ElementView.prototype.update.apply(this, arguments);
},
updateBox: function () {
// Set the position and dimension of the box so that it covers the JointJS element.
var bbox = this.model.getBBox();
// Example of updating the HTML with a data stored in the cell model.
// paper.on('blank:pointerdown', function(evt, x, y) { this.$box.find('textarea').toBack(); });
this.$box.find('span').text(this.model.get('textarea'));
this.model.on('cell:pointerclick', function (evt, x, y) {
this.$box.find('textarea').toFront();
});
this.$box.css({width: bbox.width, height: bbox.height, left: bbox.x, top: bbox.y, transform: 'rotate(' + (this.model.get('angle') || 0) + 'deg)'});
},
removeBox: function (evt) {
this.$box.remove();
}
});
// Create JointJS elements and add them to the graph as usual.
// -----------------------------------------------------------
var el1 = new joint.shapes.html.Element({
position: {x: 600, y: 250},
size: {width: 170, height: 100},
inPorts: ['in'],
outPorts: ['out'],
textarea: 'Start writing'
});
var el2 = new joint.shapes.html.Element({
position: {x: 600, y: 400},
size: {width: 170, height: 100},
inPorts: ['in'],
outPorts: ['out'],
textarea: 'Start writing'
});
graph.addCells([el1, el2]);
Also is it possible to scale the svg shape based on the text inside text area?
I assume that you are using the CSS stylesheet from the JointJS HTML tutorial (http://jointjs.com/tutorial/html-elements).
Note that .html-element has pointer-events set to none. With that being set all events are propagated to the (JointJS) SVG Element under the HTML Element. The paper therefore knows what element was interacted with and e.g. can start dragging it.
.html-element {
pointer-events: none;
}
I suggest to create an exception for the TextArea by adding the following CSS rule.
.html-element textarea {
pointer-events: all;
}

newbie: hello world using jointjs

Hello Im trying to execute Hello world application using JointJS library as given in :
http://www.jointjs.com/tutorial#hello-world
I have downloaded joint.js and joint.css files
I have copied the code given in HelloWorld tutorial in html file and accessed it from the firefox browser (26.0)
But its not working as expected and shown in the tutorial.
Expected: Two boxes with link should come.
Actual: Nothing is coming on the browser. Ater debugging error is:
"NS_ERROR_FAILURE:" in joint.js at:
var bbox = this.el.getBBox();
code is:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="joint.css" />
<script src="joint.js"></script>
</head>
<body>
<script type="text/javascript">
var graph = new joint.dia.Graph;
var paper = new joint.dia.Paper({
el: $('#myholder'),
width: 600,
height: 200,
model: graph
});
var rect = new joint.shapes.basic.Rect({
position: { x: 100, y: 30 },
size: { width: 100, height: 30 },
attrs: { rect: { fill: 'blue' }, text: { text: 'my box', fill: 'white' } }
});
var rect2 = rect.clone();
rect2.translate(300);
var link = new joint.dia.Link({
source: { id: rect.id },
target: { id: rect2.id }
});
graph.addCells([rect, rect2, link]);
</script>
</body>
</html>
Regards
Ranganath
You're missing a holder for the paper object. Add the following right after the opening <body> tag:
<div id="myholder"></div>
You can try this code. Please add jquery.min.js lodash.min.js backbone-min.js
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="joint.css" />
<script src="joint.js"></script>
<script src="jquery.min.js"></script>
<script src="lodash.min.js"></script>
<script src="backbone-min.js"></script>
</head>
<body>
<div id="myholder"></div>
<script type="text/javascript">
var graph = new joint.dia.Graph;
var paper = new joint.dia.Paper({
el: $('#myholder'),
width: 600,
height: 200,
model: graph
});
var rect = new joint.shapes.basic.Rect({
position: { x: 100, y: 30 },
size: { width: 100, height: 30 },
attrs: { rect: { fill: 'blue' }, text: { text: 'my box', fill: 'white' } }
});
var rect2 = rect.clone();
rect2.translate(300);
var link = new joint.dia.Link({
source: { id: rect.id },
target: { id: rect2.id }
});
graph.addCells([rect, rect2, link]);
</script>
</body>

Resources