JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdn.rawgit.com/photonstorm/phaser/dev/build/phaser.js"></script>
<label for="movie">Max velocity (in m/s) : </label>
<input id="maxVelocity" type="number" value="5" oninput="javascript: updateMaxVelocity(event)"/>
JavaScript
var maxVelocity = 5
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render });
window.updateMaxVelocity = function(event) {
maxVelocity = Math.abs(parseInt(event.currentTarget.value)) || 5
console.log('new updateMaxVelocity', maxVelocity)
}
function preload() {
game.load.image('stars', 'http://examples.phaser.io/assets/misc/starfield.jpg');
game.load.image('ship', 'http://examples.phaser.io/assets/sprites/thrust_ship2.png');
}
var ship;
var starfield;
var cursors;
function create() {
game.world.setBounds(0, 0, 1920, 1200);
game.physics.startSystem(Phaser.Physics.P2JS);
game.physics.p2.defaultRestitution = 0.8;
starfield = game.add.tileSprite(0, 0, 800, 600, 'stars');
starfield.fixedToCamera = true;
ship = game.add.sprite(200, 200, 'ship');
game.physics.p2.enable(ship);
game.camera.follow(ship);
cursors = game.input.keyboard.createCursorKeys();
}
//A: define your velocity constraining function
function constrainVelocity(sprite, maxVelocity) {
var body = sprite.body
var angle, currVelocitySqr, vx, vy;
vx = body.data.velocity[0];
vy = body.data.velocity[1];
currVelocitySqr = vx * vx + vy * vy;
if (currVelocitySqr > maxVelocity * maxVelocity) {
angle = Math.atan2(vy, vx);
vx = Math.cos(angle) * maxVelocity;
vy = Math.sin(angle) * maxVelocity;
body.data.velocity[0] = vx;
body.data.velocity[1] = vy;
}
};
function update() {
if (cursors.left.isDown)
{
ship.body.rotateLeft(100);
}
else if (cursors.right.isDown)
{
ship.body.rotateRight(100);
}
else
{
ship.body.setZeroRotation();
}
if (cursors.up.isDown)
{
ship.body.thrust(400);
}
else if (cursors.down.isDown)
{
ship.body.reverse(400);
}
if (!game.camera.atLimit.x)
{
starfield.tilePosition.x += (ship.body.velocity.x * 16) *...