Collision p2 physics doesnt work - javascript

I'm trying to get the collision to work in Phaser.
I'm using the p2 physics and I want a function to get called, when the player hits a door:
//Load player
playerSprite = this.game.add.sprite(50, 900, 'player-front');
player = new Player(playerSprite);
//1
//Enter door
door = this.game.add.sprite(350, 865, 'player-back');
Then i start the physics:
this.game.physics.startSystem(Phaser.Physics.P2JS);
//Setting up witch tiles needs colliders
map.setCollision(261, true, 'Collisions');
this.game.physics.p2.convertTilemap(map, 'Collisions');
this.game.physics.p2.enable([player.sprite, door], false);
player.sprite.body.fixedRotation = true;
//Physics engine create collision bodies from the tiles
this.game.physics.arcade.enable(map);
this.game.physics.setBoundsToWorld();
//
this.game.physics.p2.setImpactEvents(true);
this.game.physics.p2.updateBoundsCollisionGroup();
Then I make 2 variables and set on the collsision to the player
var playerCollisionGroup = this.game.physics.p2.createCollisionGroup();
var doorCollisionGroup = this.game.physics.p2.createCollisionGroup();
door.physicsBodyType = Phaser.Physics.P2JS;
door.body.setCollisionGroup(doorCollisionGroup);
door.body.collides(playerCollisionGroup);
player.sprite.body.setCollisionGroup(playerCollisionGroup);
player.sprite.body.collides(doorCollisionGroup, this.hitDoor, this);
And the hitDoor function looks like this:
hitDoor: function(body1, body2){
console.log("Collision works");
},
I dont know why it's now working.
Someone that can see the problem?
Ty

Related

Detection with collision in canvas phaser without physics

I have to do a mini video game for a practice. I have coded in Phaser, JavaScript and Java. The canvas is drawn in Phaser.
I need to put collisions in the borders of the world or something when my spaceship touch the canvas limit for my spaceship doesn't go out to the screen.
My teacher forbidden do something with physics like arcade, ninja, or P2.
Its doesn't matter if the solution is in JavaScript or Phaser. Only I need to put limits in the canvas' border.
I have this for drawing the world in Phaser:
game = new Phaser.Game(1024, 600, Phaser.AUTO, 'gameDiv'
I have my sprite in the world in the preload:
game.global.myPlayer.image = game.add.sprite(0, 0, 'spacewar', game.global.myPlayer.shipType);
In the create function I have the keyboard control:
this.wKey = game.input.keyboard.addKey(Phaser.Keyboard.UP);
this.sKey = game.input.keyboard.addKey(Phaser.Keyboard.DOWN);
this.aKey = game.input.keyboard.addKey(Phaser.Keyboard.LEFT);
this.dKey = game.input.keyboard.addKey(Phaser.Keyboard.RIGHT);
this.spaceKey = game.input.keyboard.addKey(Phaser.Keyboard.CONTROL);
this.shiftKey = game.input.keyboard.addKey(Phaser.Keyboard.SHIFT);
In the update function the movement:
if (this.wKey.isDown)
msg.movement.thrust = true;
if (this.sKey.isDown)
msg.movement.brake = true;
if (this.aKey.isDown)
msg.movement.rotLeft = true;
if (this.dKey.isDown)
msg.movement.rotRight = true;
if (this.spaceKey.isDown) {
msg.bullet = this.fireBullet()
}
if (this.shiftKey.isDown) {
msg.push = true;
}
Not sure how asking for the solution to a school project will help you learn anything..
But anyway, the update() function is called for every frame (60 times per second), so inside that function you can do something like this to prevent the player from moving outside the game area:
// cannot move outside game area, left and right
if (game.global.myPlayer.image.x < 0) {
game.global.myPlayer.image.x = 0;
}
if (game.global.myPlayer.image.x > game.world.width) {
game.global.myPlayer.image.x = game.world.width;
}
// cannot move outside game area, top and bottom
if (game.global.myPlayer.image.y < 0) {
game.global.myPlayer.image.y = 0;
}
if (game.global.myPlayer.image.y > game.world.height) {
game.global.myPlayer.image.y = game.world.height;
}

Having trouble resetting a group in the canvas

Ive been working on my side scrolling game that generates random aliens on the canvas. The game has basic arcade physics and shooting, Im now working on the restart function for my game and I have gotten so far as reseting the lives, score and player on the canvas. But I'm having trouble reseting the group of aliens. my code for the aliens is the create function, but when I call the create aliens function in the restart function it is out of scope. I was following this link as an example but it isnt working either.
Is there a better way to restart the group in phaser??
here is my code for the group:
//Creates a group of 35 aliens.
function createAliens(){
aliens = game.add.group();
aliens.enableBody = true;
aliens.createMultiple(35, 'aliens', 0, false);
game.time.events.repeat(Phaser.Timer.SECOND, 20, resurrect, this);
//ressurects the alien from the group and adds it to the group, and gives it movement & physics.
function resurrect() {
var ufos = aliens.getFirstDead();
if(ufos){
ufos.reset(game.world.randomX, game.world.randomY);
ufos.body.velocity.setTo(10 + Math.random() * 40, 10 + Math.random() * 40);
ufos.body.bounce.setTo(0.5, 0.5);
ufos.body.collideWorldBounds = true;
ufos.frame = game.rnd.integerInRange(0,36);
}
}
}
And here is my restart function:
function restart(){
lives.callAll('revive');
aliens.removeAll();
player.revive();
console.log(createAliens());
deadTxt.visible = false;
score = 0;
}
and my github repo if you'd like too play :)

New state with Phaser

I'm trying to switch state with a collision. So when the player hits another sprite it should switch state, but it doesn't..
First I'm declaring the player and the enterDoor sprites under create::
playerSprite = this.game.add.sprite(50, 1700, 'player-front');
player = new Player(playerSprite);
this.game.physics.enable(player, Phaser.Physics.ARCADE);
enterDoor = this.game.add.sprite(332, 830, 'player-back');
playerDoor = new Player(enterDoor);
this.game.physics.enable(playerDoor, Phaser.Physics.ARCADE);
Then I'm trying to make the overlap under update: :
this.game.physics.arcade.overlap(player, playerDoor, this.enterHouse, null, this);
And enterHouse is another function:
enterHouse: function() {
this.state.start('Menu');
}
What am I doin' wrong?
So with the code above I wasn't able to get the overlap to trigger at all. After disabling moves on the player sprite's body the overlap was triggered.
player.body.moves = false;
Your enterHouse function doesn't need to accept the two sprites, and can be left as-is.
What I don't know is why this is necessary.

Why wont my sprite appear on top of my background?

I have been practicing using sprites for a game I am going to make and have watched and read a few tutorials, I thought I was close to getting my sprite to appear so I could finally start my game but while practicing I cant get it to work, I have dont 2 seperate tutorials where I can get the sprite and the background to appear by themselfs but cannot get them to work together, I have been using EaselJS too. some of the sprite animation code has been copied from tutorials too.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>sprite prac<title>
<!-- EaselJS library -->
<script src="lib/easel.js"></script>
<script>
// Initialize on start up so game runs smoothly
function init() {
canvas = document.getElementById("canvas");
stage = new Stage(canvas);
bg = new Image();
bg.src = "img/grassbg.jpg";
bg.onload = setBG;
stage.addChild(background);
imgMonsterARun = new Image();
imgMonsterARun.onload = handleImageLoad;
imgMonsterARun.onerror = handleImageError;
imgMonsterARun.src = "img/MonsterARun.png";
stage.update();
}
function handleImageLoad(e) {
startGame();
}
// Simple function for setting up the background
function setBG(event){
var bgrnd = new Bitmap(bg);
stage.addChild(bgrnd);
stage.update();
}
function startGame() {
// create a new stage and point it at our canvas:
stage = new createjs.Stage(canvas);
// grab canvas width and height for later calculations:
screen_width = canvas.width;
screen_height = canvas.height;
// create spritesheet and assign the associated data.
var spriteSheet = new createjs.SpriteSheet({
// image to use
images: [imgMonsterARun],
// width, height & registration point of each sprite
frames: {width: 64, height: 64, regX: 32, regY: 32},
animations: {
walk: [0, 9, "walk"]
}
});
// create a BitmapAnimation instance to display and play back the sprite sheet:
bmpAnimation = new createjs.BitmapAnimation(spriteSheet);
// start playing the first sequence:
bmpAnimation.gotoAndPlay("walk"); //animate
// set up a shadow. Note that shadows are ridiculously expensive. You could display hundreds
// of animated rats if you disabled the shadow.
bmpAnimation.shadow = new createjs.Shadow("#454", 0, 5, 4);
bmpAnimation.name = "monster1";
bmpAnimation.direction = 90;
bmpAnimation.vX = 4;
bmpAnimation.x = 16;
bmpAnimation.y = 32;
// have each monster start at a specific frame
bmpAnimation.currentFrame = 0;
stage.addChild(bmpAnimation);
// we want to do some work before we update the canvas,
// otherwise we could use Ticker.addListener(stage);
createjs.Ticker.addListener(window);
createjs.Ticker.useRAF = true;
createjs.Ticker.setFPS(60);
}
//called if there is an error loading the image (usually due to a 404)
function handleImageError(e) {
console.log("Error Loading Image : " + e.target.src);
}
function tick() {
// Hit testing the screen width, otherwise our sprite would disappear
if (bmpAnimation.x >= screen_width - 16) {
// We've reached the right side of our screen
// We need to walk left now to go back to our initial position
bmpAnimation.direction = -90;
}
if (bmpAnimation.x < 16) {
// We've reached the left side of our screen
// We need to walk right now
bmpAnimation.direction = 90;
}
// Moving the sprite based on the direction & the speed
if (bmpAnimation.direction == 90) {
bmpAnimation.x += bmpAnimation.vX;
}
else {
bmpAnimation.x -= bmpAnimation.vX;
}
// update the stage:
stage.update();
}
</script>
</head>
<body onload="init();">
<canvas id="canvas" width="500" height="500" style="border: thin black solid;" ></canvas>
</body>
</html>
There are a few places where you are using some really old APIs, which may or may not be supported depending on your version of EaselJS. Where did you get the easel.js script you reference?
Assuming you have a version of EaselJS that matches the APIs you are using, there are a few issues:
You add background to the stage. There is no background, so you are probably getting an error when you add it. You already add bgrnd in the setBackground method, which should be fine. If you get an error here, then this could be your main issue.
You don't need to update the stage any time you add something, just when you want the stage to "refresh". In your code, you update after setting the background, and again immediately at the end of your init(). These will fire one after the other.
Are you getting errors in your console? That would be a good place to start debugging. I would also recommend posting code if you can to show an actual demo if you continue to have issues, which will help identify what is happening.
If you have a newer version of EaselJS:
BitmapAnimation is now Sprite, and doesn't support direction. To flip Sprites, use scaleX=-1
Ticker no longer uses addListener. Instead it uses the EventDispatcher. createjs.Ticker.addEventListener("tick", tickFunction);
You can get new versions of the CreateJS libraries at http://code.createjs.com, and you can get updated examples and code on the website and GitHub.

CreateJS FPS drop when calling stage.update

I'm making a game using CreateJS. On desktop my FPS is good but when I try to play this game on mobile (for example : iPhone 4) the FPS drops seriously.
I'm trying to figure out why but
Some code
My Canvas
<canvas id="gameCanvas"></canvas>
Setup
this.canvas = "gameCanvas";
this.stage = new createjs.Stage(this.canvas);
var context = this.stage.canvas.getContext("2d");
context.imageSmoothingEnabled = false;
createjs.Ticker.setFPS(30);
this.gameLoopBind = this.gameLoop.bind(this);
createjs.Ticker.addEventListener('tick', this.gameLoopBind);
GameLoop
// some extra code
this.stage.update();
When I comment the code 'this.stage.update()' my FPS on mobile/tablet is good...
I've no idea what I'm doing wrong...
EXTRA CODE
Play the game here => f.cowb.eu/mora/chick-ins
Gameloop Function
Game.prototype.gameLoop = function (e) {
if (this.running) {
this.timer++;
this.timer2++;
if (this.timer2 > 30) {
if (this.lastSnack + this.timeBewteen < this.stopwatch.seconds) {
var height = (this.topSnack) ? 150 : 300;
this.lastSnack = this.stopwatch.seconds;
new Snack(this, this.timer, height);
this.topSnack = this.topSnack ? false : true;
}
if (this.timer > (this.lastPostive + 300)) {
this.lastPostive = this.timer;
publisher.publish('showMessage',
this.positiveImages[Math.floor(Math.random() * this.positiveImages.length)],
common.lang,
'right');
}
this.timer2 = 0;
}
}
this.stage.update();
};
New Snack
You can find the code for creating a new snack here => http://jsfiddle.net/9ofpqq3z/
Here we create a new snack and animate it.
From looking at the architecture of the game, I would suggest that you draw the game elements on separate canvases as opposed to the way you have it right now where everything is on one canvas.
Place the TV parts that don't get redrawn often (or at all) on one canvas, and then the moving elements on a separate canvas.
That should help bring the frame rate up.
Also, you can take a look at the following set of slides on how to improve performance on mobile devices when using the canvas:
http://www.slideshare.net/DavidGoemans/html5-performance-optimization

Categories