JSFiddle - React, Tailwind, and code Playground
by D Sami
HTML
<script src="https://github.com/photonstorm/phaser-ce/releases/download/v2.7.5/phaser.min.js"></script>
JavaScript
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', {
preload: preload,
create: create,
update: update,
render: render
});
var player;
var ai;
var surface;
function preload() {
game.load.image('fish','https://lh4.googleusercontent.com/yCJtTB6b9v0ewFtWqgi6fpBnBGy9BPGlQvj7rVJliBzGA3oomzo4fQNg2yowdiMLqwKBSfQ1Uv3Ieh44nZlTVBOQDTkw5amkCvKK2TJ05pbBlmuOptj4le7rFR8OjGNx5w');
}
function create() {
game.stage.backgroundColor ='#3e5f96';
game.physics.startSystem(Phaser.Physics.P2JS);
surface =game.add.sprite(400,100);
game.physics.p2.enable(surface);
surface.body.setRectangle(500,10);
surface.body.static=true;
player=new Fish(400,300,0.5,0.5);
ai=new enemyFish(100,500,0.3,0.3);
surface.body.debug=true;
player.fishBody.debug=true;
ai.fishBody.debug=true;
}
function update() {
playerInput();
player.avoid(player.fishBody.x,player.fishBody.y,surface.body.x,surface.body.y);
}
function render() {
game.debug.text("IJKL: movement",300,50);
}
var Fish=function(xpos,ypos,xscale,yscale){
this.sprite=game.add.sprite(xpos, ypos,'fish');
this.sprite.scale.setTo(xscale,yscale);
game.physics.p2.enable(this.sprite);
this.fishBody=this.sprite.body;
//manipulate the body dimens
this.fishBody.setRectangle(10,50);
};
var enemyFish=function(xpos,ypos,xscale,yscale){
Fish.call(this,xpos,ypos,xscale,yscale);
this.fishBody.velocity.x=80;
}
Fish.prototype.avoid = function(fishBodx, FishBodY, xsp,ysp){
var targetAngle = Phaser.Math.angleBetween(xsp, ysp, fishBodx, FishBodY);
//console.log(targetAngle);
if (this.fishBody.rotation !== targetAngle) {
var delta = (targetAngle) - (this.fishBody.rotation);
this.TURN_RATE = 3;
// Keep it in range from -180 to 180 to make the most efficient turns.
if (delta > Math.PI) delta -= Math.PI * 2;
if (delta < -Math.PI) delta += Math.PI * 2;
if (delta > 0) {
// Turn clockwise
this.fishBody.angle +=...