javascript collision for game - javascript

The issue I'm having is when an npc and player are within 5 pixels a collision is triggered and then the npc's inventory is displayed in the console. The problem is that the npc inventory will only display this once.
I would like to make it so that every time the player is within 5 pixels of the npc their inventory is displayed. But also I don't want the collision to trigger constantly while the player is within 5 pixels of the npc, just once when they first get close.
Here's my code...
// collision for npc and player
function npc2Collision(){
for(var i = 0; i < 1; i++){
game.addEventListener('enterframe', function() {
//detects whether player sprite is within 5
//pixels of the npc sprite
if(player.within(npc2,5) && !npc2.isHit){
console.table(npcInvObject);
npc2.isHit = true;
}
});
}
}
npc2Collision();

To prevent the collision from firing again, you can use a simple flag set by the check (and its inverse):
function npc2Collision(){
for(var i = 0; i < 1; i++){
game.addEventListener('enterframe', function() {
//detects whether player sprite is within 5
//pixels of the npc sprite
if(player.within(npc2,5) && !npc2.isHit){
// split the checks so distance works well
if (!player.collided) {
console.table(npcInvObject);
npc2.isHit = true;
player.collided = true;
}
} else {
player.collided = false;
});
}
}
This will run once, set the collided flag on the player, and will not fire again until the player has left the collision radius.

Related

P5.Play - Collision problems

hoping someone can help me with this.
I'm trying to create a game where balloons get popped by bullet.
Sort of similar to balloons tower defence. My only problem is that the frames are drawn every 60 seconds and each loop happens once per 60 seconds meaning that the bullet getting removed happens before the balloons change.
So far I've got:
Bullet is fired.
Bullets checks whether it has hit a balloon.
If hit remove bullet and change blue balloon to red balloon.
This would be easier if there was some way of checking which bullet collides with which balloon but as far as I can tell through the P5.Play reference theres no way to do this.
Sorry if this is stupid question I feel like I've been stuck on this issue for ages :(
Thanks for the help!
Code:
Bullets:
function bulletTime() {
bullet = createSprite(player.position.x, player.position.y, 3, 10);
bullet.setSpeed(4, 270);
bullet.setCollider("rectangle", 0, -2, 3, 10);
bullet.debug = true;
bullet.addToGroup(bullets);
}
// deletes bullets when they leave the screen prevents memory overload
function bulletDelete(){
for (i = 0; i < bullets.length; i++) {
if (bullets[i].overlap(balloons)){
bullet2 = createSprite(bullets[i].position.x, bullets[i].position.y+3, 3, 10);
bullet2.addToGroup(bullets2);
bullets[i].remove();
setTimeout(bullet2.remove(),10);
}
}
}
Balloons:
// pops Balloons
function popBalloon(){
for (i = 0; i < balloons.length; i++) {
if (balloons[i].overlap(bullets2)) {
if (balloonsRed.contains(balloons[i])){
balloons[i].addImage("redPop",redPop);
balloons[i].changeAnimation("redPop");
balloons[i].remove();
score += 100;
}
if (balloonsBlue.contains(balloons[i]) ){
balloons[i].addImage("redBalloon",redBalloon);
balloons[i].changeAnimation("redBalloon");
balloons[i].addToGroup(recentlyHit);
}
}
}
}
In case anyone else has a similar issue. HardcoreGameDev had it right!
Here's the working code.
// pops Balloons
function popBalloon(){
for (j = 0; j < balloons.length; j++) {
for (i = 0; i < bullets.length; i++) {
if (bullets[i].overlap(balloons[j])){
if (balloonsRed.contains(balloons[j])){
bullets[i].remove();
balloons[j].remove();
return;
}
if (balloonsBlue.contains(balloons[j])){
print("blue")
bullets[i].remove();
balloon = createSprite(balloons[j].position.x, balloons[j].position.y, 30, 30);
balloon.addSpeed(0.5,90);
balloon.addToGroup(balloons);
balloon.debug = true;
balloon.addImage("red",redBalloon);
balloon.changeAnimation("red");
balloon.scale = 0.2;
balloon.setCollider("circle",0,0,120);
balloon.addToGroup(balloonsRed);
balloons[j].remove();
return;
}
}
}
}
}
I know the code is arbitrary at some points :)
Your issue seems to related to your step 3.
If hit remove bullet and change blue balloon to red balloon.
The bullet attempted to remove itself / delete when a collision happens.
This actually implemented as "when the bullet hit a balloon the bullet disappears", so the balloon may never detect any collisions.
Since the balloon states are triggered by bullet, the popBalloon function should be called inside bulletDelete to update the specific balloon that got hit.

Phaser3 framework javascript: current anims index

In phaser 3 framework, what syntax do I use to check the current frame index?
I want to make a hit area appear only when the player's sprite sheet reaches a certain index(the index displaying the motion of 'attack'). I want to accomplish this through detecting its current frame index.
How can I do this?
You could use the sprite events like: Phaser.Animations.Events.ANIMATION_UPDATE, details in official phaser documenation
player.on(Phaser.Animations.Events.ANIMATION_UPDATE, function (anim, frame, gameObject, frameKey) {
// Here you can check for the specific-frame
if(frameKey == "show_hit_area_frame"){
// ... show hitarea
}
// alternatively: with the index of the frame
if(frame.index == 7){
// ... show hitarea
}
});
In this selected Event, you can also check the current frame, for other properties of the frame object (details in official documenation), if you don't know/have the specific framekey/index.
The solution is found.
//hitbox solution: https://newdocs.phaser.io/docs/3.52.0/Phaser.Animations.Events.ANIMATION_COMPLETE_KEY
//hitboxB listener
gameState.playerB.on('animationstart-kill', function () {
console.log("finish kill <3")
gameState.hitBoxB.x = gameState.playerB.flipX ? gameState.playerB.x + 120 : gameState.playerB.x - 120;
gameState.hitBoxB.y = gameState.playerB.y;
// gameState.hitBoxB.visible = true;
})
gameState.playerB.on('animationcomplete-kill', function () {
console.log("kill <3")
gameState.hitBoxB.x =0 ;
gameState.hitBoxB.y = 0;
// gameState.hitBoxB.visible = false;
})

CreateJs - Controlling timeline playhead with click & drag

First time posting here, hope I'm doing this right :) I am trying to create a 360 spin in Adobe Animate with createJS, using a sequence of images embedded in a MovieClip. I have managed to get control of the timeline playhead using the code below:-
var start_x;
var startFrame;
var changeDistance;
var travelDistance;
this.threeSixty.addEventListener("mousedown", onMouseDown.bind(this));
this.threeSixty.addEventListener("pressup", onMouseUp.bind(this));
function onMouseDown(e) {
start_x = e.stageX;
startFrame = this.threeSixty.timeline.position;
this.threeSixty.addEventListener("pressmove", onMouseMove.bind(this));
}
function onMouseUp(e) {
this.threeSixty.removeEventListener("pressmove", onMouseMove.bind(this));
}
function onMouseMove(e) {
var changeDistance = e.stageX-start_x;
var travelDistance = startFrame+changeDistance;
if (travelDistance > this.threeSixty.timeline.duration){
this.threeSixty.gotoAndStop(travelDistance % this.threeSixty.timeline.duration);
}else if (travelDistance < 0){
this.threeSixty.gotoAndStop (this.threeSixty.timeline.duration + (travelDistance % threeSixty.timeline.duration));
} else {
this.threeSixty.gotoAndStop(travelDistance);
}
}
The problem is, when you click and drag the image along the X axis, the image sequence only moves forward/backwards by a single frame, as opposed to continuing the image sequence until the either mouse has stopped moving, or the mouse click is released. Any ideas where I might be going wrong here?
Thanks

Easeljs sprite animation stuck on frame

I'm learning javascript by using the easeljs library to make a simple game, for school lessons.
I want to make a crosshair give some feedback to the player by showing a small animation while you are pointing at your target, using a hittest I made.
However, when the crosshair touches the target, the animation (should be two little triangles pointing to the middle of the crosshair) seems to be stuck on it's first frame.
Here is a bit of my code, I put both of these functions inside a ticker function. The functions do what they're supposed to do (I checked by sending a message to the console.log), but I think the animation is reset as soon as the variable "hitTestControle" is set to true, at every tick.
If you want to check out all of the code, here is a link to the "game":
http://athena.fhict.nl/users/i279907/achtergrond/achtergrond.html
function hitTest() {
if(distance(crossHair, block) < 60) {
hitTestControle = true;
} else {
hitTestControle = false;
console.log(hitTestControle);
}
}
function hitTestControl() {
if(hitTestControle == true) {
crossHair.gotoAndPlay("move");
console.log("hit");
} else {
crossHair.gotoAndPlay("stop");
}
}
PS: There also seems to be something wrong with this hittest I used.
function distance() {
var difx = blok.x - crossHair.x;
var dify = blok.y - crossHair.y;
return Math.sqrt( (difx * difx) + (dify * dify) );
}
It looks like you're starting the animation... setting it to the first frame and starting it... every time hitTestControle is true. Since hitTestControle will be true as long as you're hovering over the target, the animation will never reach the second frame.
What you need to do is start the animation when you transition from hitTestControle = false to hitTestControle = true, but once that happens you just let it play automatically.
Try changing your hitTestControl() function to something like this:
function hitTestControl() {
if(hitTestControle == true && alreadyOverHit == false) {
crossHair.gotoAndPlay("move");
alreadyOverHit = true;
console.log("hit");
} else {
crossHair.gotoAndPlay("stop");
alreadyOverHit = false;
}
}
In other words, only start the animation once, during the first frame you're detecting a hit, and then don't touch it unless you move off the target and back on.

gameQuery collision detection

it is the first time for me to explore jQuery and gameQuery for building games using JavaScript, so am asking about sth that might look very naive, but really i cant get it.
i am developing a game like Space Invader, the detection for collision between player missile and enemies not working.
This is my code:
the definition for my Enemy class
function Enemy(node){
this.node = $(node);
this.pts_value = 0;
return true;
}
this is the code i use to add ten enemy sprite next to each other. the enemies move together to the left and the right
$.each(new Array(10), function(index, value) {
$("#enemy_group").addSprite("enemy2_"+index,{animation: enemies[2],
posx: index * 55, posy: 0, width: 48, height: 48})
$("#enemy2_"+index).addClass("enemy");
$("#enemy2_"+index)[0].enemy = new Enemy($("#enemy2_"+index));
$("#enemy2_"+index)[0].pts_value = 150;
});
so when i need to move the enemies, i move the enemies together, i move the group that includes all the sprites "#enemy_group"
if(ENEMY_TO_RIGHT){
var enemiesNewPos = (parseInt($("#enemy_group").css("left"))) + ENEMY_SPEED;
if(enemiesNewPos < PLAYGROUND_WIDTH - 550){
$("#enemy_group").css("left", ""+enemiesNewPos+"px");
} else {
ENEMY_TO_RIGHT = false;
}
} else {
var enemiesNewPos = (parseInt($("#enemy_group").css("left"))) - ENEMY_SPEED;
if(enemiesNewPos > 0){
$("#enemy_group").css("left", ""+enemiesNewPos+"px");
} else {
ENEMY_TO_RIGHT = true;
}
}
finally for collision detection, i want to remove the enemy sprite that the players missile has hit, each missile sprite has an added class names ".playerMissiles"
$(".playerMissiles").each(function(){
var posy = parseInt($(this).css("top"));
if(posy < 0){
$(this).remove();
return;
}
$(this).css("top", ""+(posy - MISSILE_SPEED)+"px");
//Test for collisions
var collided = $(this).collision(".enemy, .group");
if(collided.length > 0){
//An enemy has been hit!
collided.each(function(){
$(this).setAnimation(enemies[0], function(node){$(node).remove();});
})
}
});
i was following the documentation tutorial on the gameQuery website.
any help appreciated, thanks,
I can't see any problem with your code. I can only give you a few pointers:
Did you create "enemy_group" with the addGroup function?
Is "enemy_group" nested in something special like a custom div ? for the collision detection to work you need a chain of parent composed only of sprites and groups (and tiles map)
Is "enemy_group" nested in a sprite, if so it's a bad idea because you will need to add the selector for this sprite in your methode call and this sprite will be included in the colliding element list.
The same goes for the ".playerMissiles"
Just to be sure what version of gameQuery and jQuery do you use? The last version from gitHub is unstable and I wouldn't recomend using it, user 0.5.1 instead.
You could use jquery collision plugin, so you avoid doid the logic by yourself.
Hope this helps. Cheers

Categories

Resources