How to collide using OOP JavaScript? - javascript

I am making a game(shooting game) using OOP javascript for my project. I already moved(player) and make the enemy disappear at the edge of the container. Now, I want to collide with the shooter(player) and enemy and display the message "Game Over". Here is my code of enemy.js and shooter.js. Also, my container.js.
container.js
class Container{
constructor(){
this.containerElement = document.getElementsByClassName("container")[0];
}
initialization(){
this.shooterElement = document.getElementsByClassName("shooter")[0];
let containerElement = document.getElementsByClassName("container")[0];
this.backgroundElement = document.getElementsByClassName("background")[0];
this.background = new Background(this.backgroundElement);
this.shooter = new Shooter(this.shooterElement);
document.addEventListener('keydown', (e)=>this.shooter.buttonGotPressed(e));
let enemyElement = document.getElementsByClassName("enemy")[0];
this.enemies = [];
setInterval(function(){
var top = Math.floor(Math.random() * 50) + 1;
var left = Math.floor(Math.random() * 550) + 1;
this.enemy = new Enemy({parentElement: containerElement, leftPosition: left, topPosition: top});
},400)
this.enemies.push(this.enemy);
}
}
let container = new Container();
container.initialization();
enemy.js
class Enemy{
constructor({parentElement,leftPosition, topPosition }){
let enemyElement = document.createElement("div");
this.enemyElement = enemyElement;
this.leftPosition = leftPosition;
this.topPosition = topPosition;
this.containerHeight = 600;
this.y = 15;
this.height = 40;
this.width = 50;
this.enemyElement.style.left = this.leftPosition + 'px';
this.enemyElement.style.top= this.topPosition + 'px';
this.enemyElement.style.height = this.height + 'px';
this.enemyElement.style.width = this.width + 'px';
this.enemyElement.style.position = "absolute";
this.enemyElement.style.background="url(images/enemy3.png)";
console.log(enemyElement)
parentElement.appendChild(this.enemyElement);
this.containerCollision = this.containerCollision.bind(this);
setInterval(this.containerCollision, 100);
}
containerCollision(){
if(this.topPosition >= this.containerHeight - this.width ){
this.enemyElement.style.display="none";
}
this.topPosition = this.topPosition + this.y;
this.enemyElement.style.top = this.topPosition + 'px';
}
}
shooter.js (this is the player)
class Shooter {
constructor(shooterElement){
this.shooterElement = shooterElement;
this.shooterleftPosition = 300;
this.shootertopPosition = 555;
this.containerWidth = 600;
this.width = 30;
this.height = 40;
this.x = 5;
this.y = 1;
this.shooterElement.style.left = this.shooterleftPosition + 'px';
this.shooterElement.style.top = this.shootertopPosition + 'px';
this.buttonGotPressed = this.buttonGotPressed.bind(this);
}
buttonGotPressed(e){
console.log(e);
if(e.key == "ArrowLeft"){
console.log(e.key);
if(this.shooterleftPosition <= 0){
this.shooterleftPosition = 0;
}
else
{
this.shooterleftPosition = this.shooterleftPosition - this.x;
}
console.log(this.shooterleftPosition)
this.shooterElement.style.left = this.shooterleftPosition +'px';
}
if(e.key == "ArrowRight"){
this.shooterleftPosition = this.shooterleftPosition + this.x;
this.shooterElement.style.left = this.shooterleftPosition +'px';
if(this.shooterleftPosition >= this.containerWidth - this.width){
this.shooterleftPosition = this.containerWidth - this.width;
this.shooterElement.style.left = this.leftPosition + 'px';
}
}
}
}
Now, How do I detect and collide shooter(player) and enemy and display the message/alert "Game Over". If the enemy touches the shooter(player). Here is pic too.
How do i know enemy touched the player and display game over in this pic
What I tried to detect the collision of player and enemy
collidingShooter(){
if (this.enemies.push(this.enemy)>1)
{
(
([this.enemies][this.enemy].top <= this.shootertopPosition + 50) &&
([this.enemies][this.enemy].top >= this.shootertopPosition) &&
([this.enemies][this.enemy].left >= this.shooterleftPosition) &&
([this.enemies][this.enemy].left <= this.shooterleftPosition+ 50)
)
console.log("hitttt");
this.enemies.splice(this.enemy,1);
// this.shooterElement.splice(1);
}
}

I believe that you messed something up here
First of all you use array in the wrong way:
[this.enemies][this.enemy].top
What it does:
Creates new array with one element (which is this.enemies array), now it converts this.enemy to a string = 'object Object' and tries to find a key in this new array, which propably returns undefined and now it tries to get top of undefined.
What you probably wanted to do is:
this.enemies[this.enemies.indexOf(this.enemy)].top
But even though it has no oop sense.
What I would do:
function checkCollision() {
for (let i = 0; i < this.enemies.length; i++) {
if (areColliding(this.shooter, this.enemies[i])) {
console.log('hit')
}
}
}
function areColliding(o1, o2) {
if (o1.top <= o2.top + o2.height &&
o1.top >= o2.top &&
o1.left <= o2.left + o2.width &&
o1.left >= o2.left) {
return true
}
return false
}
There are better collision algorithms than aabb and even if you want to do this in this way, your game can get very slow if you have thousands of enemies. There is algorithm to split game world in to smaller rectangles and check for collision inside them.

Related

When spawning many iterations of a class object, how do I take an object out of the array using a if statement inside of the Class?

I'm a beginner using p5js and I'm trying to work with classes. I'm making a game where you have to find and click a 'wanted man', from a crowd.
So basically, a randomizer picks between 7 different types of 'civilians', and it's supposed to remove one of the types from the 'civilians' that have been spawned. After removing the 'wanted man', I want to add one wanted man so that there is only one 'wanted man'.
So the code spawns a bunch of random 'civilians', then it will delete all 'wanted man' types in the array, and add only one of them. I think there is a better way to do this though.
My basic desire is to have a crowd of 'civilians' that run around, - one of which is a 'wanted man' - and you would have to find and click that 'wanted man' (kind of like a hunting/assassination game).
This is the code for the sketch.js file:
var civilians = [];
var page = 0;
var man1img;
var man2img;
var man3img;
var man4img;
var man5img;
var man6img;
var aliemanimg;
var w;
var h;
var spawnCount = 14;
var wantedMan;
var randCiv;
function preload() {
man1img = loadImage("man1.png");
man2img = loadImage("man2.png");
man3img = loadImage("man3.png");
man4img = loadImage("man4.png");
man5img = loadImage("man5.png");
man6img = loadImage("man6.png");
aliemanimg = loadImage("alieman.png");
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}
function setup() {
createCanvas(windowWidth, windowHeight);
imageMode(CENTER);
// wantedMan = round(random(0, 6));
wantedMan = 0;
for (var i = 0; i < spawnCount; i++) {
randCiv = round(random(0, 6));
w = random(windowWidth);
h = random(windowHeight);
civilians.push(new Civilian(w, h, wantedMan, randCiv));
console.log(wantedMan);
if (civilians[i].isWantedMan()) {
//OVER HERE \/
civilians.splice(i, 1);
}
}
civilians.push(new Civilian(w, h, wantedMan, wantedMan));
}
// page setup
// page 1 : main screen (play, settings, and those stuff)
// page 2 : show chosen civilian
// page 3 : playing
// page 4 : lose
// page 5 : options
function draw() {
background(220, 80, 80);
for (var i = civilians.length - 1; i >= 0; i--) {
civilians[i].update();
civilians[i].show(mouseX, mouseY);
if (civilians[i].clickedOn(mouseX, mouseY)) {
// detect if is right person
console.log("clicked on boi");
if (civilians[i].isWantedMan()) {
console.log("HES WANTED");
} else {
console.log("HES NOT WANTED");
}
}
}
text(round(frameRate()), 20, 20);
//show wanted man
var tempImg = man1img;
if (wantedMan == 1) {
tempImg = man2img;
} else if (wantedMan == 2) {
tempImg = man3img;
} else if (wantedMan == 3) {
tempImg = man4img;
}
if (wantedMan == 4) {
tempImg = man5img;
} else if (wantedMan == 5) {
tempImg = man6img;
} else if (wantedMan == 6) {
tempImg = aliemanimg;
}
image(tempImg, 50, 70, 70, 90);
}
This is the code for the class:
class Civilian {
constructor(x, y, wantedMan, type) {
this.x = x;
this.y = y;
this.w = 47;
this.h = 60;
this.t = {
x: x,
y: y,
};
this.size = 47;
this.moveSpeed = 0.01;
this.moveDist = 20;
this.wantedMan = wantedMan;
this.civilian = type
this.civilianImg = man1img
this.wantedMan = wantedMan
}
update() {
//move target to random position
this.t.x = random(this.t.x - this.moveDist, this.t.x + this.moveDist);
this.t.y = random(this.t.y - this.moveDist, this.t.y + this.moveDist);
//edge detect
if (this.t.x < 0) {
this.t.x += 5;
}
if (this.t.x > width) {
this.t.x -= 5;
}
if (this.t.y < 0) {
this.t.y += 5;
}
if (this.t.y > height) {
this.t.y -= 5;
}
//images position follows target but with easing
this.x += (this.t.x - this.x) * this.moveSpeed;
this.y += (this.t.y - this.y) * this.moveSpeed;
}
show(ex, ey) {
var d = dist(ex, ey, this.x, this.y);
if (d > this.size / 2) {
tint(255, 255, 255);
} else {
tint(0, 255, 0);
}
if(this.civilian == 1) {
this.civilianImg = man2img
} else if(this.civilian == 2) {
this.civilianImg = man3img
} else if(this.civilian ==3) {
this.civilianImg = man4img
} if(this.civilian == 4) {
this.civilianImg = man5img
} else if(this.civilian == 5) {
this.civilianImg = man6img
} else if(this.civilian == 6) {
this.civilianImg = aliemanimg
}
image(this.civilianImg, this.x, this.y, 47, 60);
}
clickedOn(ex, ey) {
var d = dist(ex, ey, this.x, this.y);
return d < this.size / 2 && mouseIsPressed;
}
isWantedMan() {
return this.civilian == this.wantedMan;
}
}
However, whenever I add a .splice(i,1) under the 'for' loop in setup function - to remove the 'wanted man', it shows this error:
"TypeError: Cannot read properties of undefined (reading
'isWantedMan') at /sketch.js:41:22".
isWantedMan() is a function in the Civilian Class, that returns true if the current 'civilian' is wanted. The .splice is supposed to remove a object from the array, when it is a 'wanted man'.
I don't know why this happens. When I replace the .splice code with a console.log() code, then there is no error.
Also there were probably a lot of things that I could have done better in the code.

Random movement of circles created by the script

I have a function that craeates divs with a circle.
Now they are all created and appear at the beginning of the page and go further in order.
Next, I need each circle to appear in a random place. I did this.
Now I need all of them to move randomly across the entire page, I have difficulties with this.
Here is an example of how everything works for one element that is already on the page.
https://jsfiddle.net/quej8wko/
But when I add this code, all my created circles don't move.
I get an error:
"message": "Uncaught TypeError: Cannot set properties of null (setting 'willChange')",
This is probably due to the fact that initially there are no circles on the page. How can I connect the code so that all created circles move?
//creating circles
var widthHeight = 40; // <-- circle width
var margin = 20; // <-- margin - is it necessary ?
var delta = widthHeight + margin;
function createDiv(id, color) {
let div = document.createElement('div');
var currentTop = 0;
var documentHeight = document.documentElement.clientHeight;
var documentWidth = document.documentElement.clientWidth;
div.setAttribute('class', id);
if (color === undefined) {
let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547'];
div.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
}
else {
div.style.backgroundColor = color;
}
div.classList.add("circle");
div.classList.add("animation");
// Get the random positions minus the delta
currentTop = Math.floor(Math.random() * documentHeight) - delta;
currentLeft = Math.floor(Math.random() * documentWidth) - delta;
// Keep the positions between -20px and the current positions
var limitedTop = Math.max(margin * -1, currentTop);
var limitedLeft = Math.max(margin * -1, currentLeft);
div.style.top = limitedTop + "px";
div.style.left = limitedLeft + "px";
document.body.appendChild(div);
}
let i = 0;
const oneSecond = 1000;
setInterval(() => {
i += 1;
createDiv(`circle${i}`)
}, oneSecond);
//move circles
function RandomObjectMover(obj, container) {
this.$object = obj;
this.$container = container;
this.container_is_window = container === window;
this.pixels_per_second = 250;
this.current_position = { x: 0, y: 0 };
this.is_running = false;
}
// Set the speed of movement in Pixels per Second.
RandomObjectMover.prototype.setSpeed = function(pxPerSec) {
this.pixels_per_second = pxPerSec;
}
RandomObjectMover.prototype._getContainerDimensions = function() {
if (this.$container === window) {
return { 'height' : this.$container.innerHeight, 'width' : this.$container.innerWidth };
} else {
return { 'height' : this.$container.clientHeight, 'width' : this.$container.clientWidth };
}
}
RandomObjectMover.prototype._generateNewPosition = function() {
// Get container dimensions minus div size
var containerSize = this._getContainerDimensions();
var availableHeight = containerSize.height - this.$object.clientHeight;
var availableWidth = containerSize.width - this.$object.clientHeight;
// Pick a random place in the space
var y = Math.floor(Math.random() * availableHeight);
var x = Math.floor(Math.random() * availableWidth);
return { x: x, y: y };
}
RandomObjectMover.prototype._calcDelta = function(a, b) {
var dx = a.x - b.x;
var dy = a.y - b.y;
var dist = Math.sqrt( dx*dx + dy*dy );
return dist;
}
RandomObjectMover.prototype._moveOnce = function() {
// Pick a new spot on the page
var next = this._generateNewPosition();
// How far do we have to move?
var delta = this._calcDelta(this.current_position, next);
// Speed of this transition, rounded to 2DP
var speed = Math.round((delta / this.pixels_per_second) * 100) / 100;
//console.log(this.current_position, next, delta, speed);
this.$object.style.transition='transform '+speed+'s linear';
this.$object.style.transform='translate3d('+next.x+'px, '+next.y+'px, 0)';
// Save this new position ready for the next call.
this.current_position = next;
};
RandomObjectMover.prototype.start = function() {
if (this.is_running) {
return;
}
// Make sure our object has the right css set
this.$object.willChange = 'transform';
this.$object.pointerEvents = 'auto';
this.boundEvent = this._moveOnce.bind(this)
// Bind callback to keep things moving
this.$object.addEventListener('transitionend', this.boundEvent);
// Start it moving
this._moveOnce();
this.is_running = true;
}
RandomObjectMover.prototype.stop = function() {
if (!this.is_running) {
return;
}
this.$object.removeEventListener('transitionend', this.boundEvent);
this.is_running = false;
}
// Init it
var x = new RandomObjectMover(document.querySelector(".circle"), window);
// Start it off
x.start();
.circle {
clip-path: circle(50%);
height: 40px;
width: 40px;
margin: 20px;
position: absolute;
}
I have modified the snippet which works as you expected.
There was a mistake where you were initializing and creating the object instance only once and none of the div elements that you created inside the setInterval function never got Instantiated.
I think you are just starting out with JavaScript with this sample project.
Below are few suggestions:
Learn to debug the code. You should be using dev tools by making use of debugger statement where it takes you to the source code to analyze the variable scope and stack during the runtime. console.log also helps in few situations.
I could see a lot of confusing naming convention (You have named the create div parameter as id but creating a div class using that id)
Try using ES6 features (class syntax is really good when writing OOP in JS although it's just a syntactic sugar for prototype)
//creating circles
var widthHeight = 40; // <-- circle width
var margin = 20; // <-- margin - is it necessary ?
var delta = widthHeight + margin;
function createAndInitializeDivObject(id, color) {
let div = document.createElement('div');
var currentTop = 0;
var documentHeight = document.documentElement.clientHeight;
var documentWidth = document.documentElement.clientWidth;
div.setAttribute('class', id);
if (color === undefined) {
let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547'];
div.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
}
else {
div.style.backgroundColor = color;
}
div.classList.add("circle");
div.classList.add("animation");
// Get the random positions minus the delta
currentTop = Math.floor(Math.random() * documentHeight) - delta;
currentLeft = Math.floor(Math.random() * documentWidth) - delta;
// Keep the positions between -20px and the current positions
var limitedTop = Math.max(margin * -1, currentTop);
var limitedLeft = Math.max(margin * -1, currentLeft);
div.style.top = limitedTop + "px";
div.style.left = limitedLeft + "px";
document.body.appendChild(div);
var x = new RandomObjectMover(document.querySelector(`.${id}`), window);
x.start();
}
let i = 0;
const oneSecond = 1000;
setInterval(() => {
i += 1;
createAndInitializeDivObject(`circle${i}`)
}, oneSecond);
//move circles
function RandomObjectMover(obj, container) {
this.$object = obj;
this.$container = container;
this.container_is_window = container === window;
this.pixels_per_second = 250;
this.current_position = { x: 0, y: 0 };
this.is_running = false;
}
// Set the speed of movement in Pixels per Second.
RandomObjectMover.prototype.setSpeed = function(pxPerSec) {
this.pixels_per_second = pxPerSec;
}
RandomObjectMover.prototype._getContainerDimensions = function() {
if (this.$container === window) {
return { 'height' : this.$container.innerHeight, 'width' : this.$container.innerWidth };
} else {
return { 'height' : this.$container.clientHeight, 'width' : this.$container.clientWidth };
}
}
RandomObjectMover.prototype._generateNewPosition = function() {
// Get container dimensions minus div size
var containerSize = this._getContainerDimensions();
var availableHeight = containerSize.height - this.$object.clientHeight;
var availableWidth = containerSize.width - this.$object.clientHeight;
// Pick a random place in the space
var y = Math.floor(Math.random() * availableHeight);
var x = Math.floor(Math.random() * availableWidth);
return { x: x, y: y };
}
RandomObjectMover.prototype._calcDelta = function(a, b) {
var dx = a.x - b.x;
var dy = a.y - b.y;
var dist = Math.sqrt( dx*dx + dy*dy );
return dist;
}
RandomObjectMover.prototype._moveOnce = function() {
// Pick a new spot on the page
var next = this._generateNewPosition();
// How far do we have to move?
var delta = this._calcDelta(this.current_position, next);
// Speed of this transition, rounded to 2DP
var speed = Math.round((delta / this.pixels_per_second) * 100) / 100;
//console.log(this.current_position, next, delta, speed);
this.$object.style.transition='transform '+speed+'s linear';
this.$object.style.transform='translate3d('+next.x+'px, '+next.y+'px, 0)';
// Save this new position ready for the next call.
this.current_position = next;
};
RandomObjectMover.prototype.start = function() {
if (this.is_running) {
return;
}
// Make sure our object has the right css set
this.$object.willChange = 'transform';
this.$object.pointerEvents = 'auto';
this.boundEvent = this._moveOnce.bind(this)
// Bind callback to keep things moving
this.$object.addEventListener('transitionend', this.boundEvent);
// Start it moving
this._moveOnce();
this.is_running = true;
}
RandomObjectMover.prototype.stop = function() {
if (!this.is_running) {
return;
}
this.$object.removeEventListener('transitionend', this.boundEvent);
this.is_running = false;
}
// Init it
var x = new RandomObjectMover(document.querySelector(".circle"), window);
// Start it off
x.start();
.circle {
width: 35px;
height: 35px;
border-radius: 35px;
background-color: #ffffff;
border: 3px solid purple;
position: absolute;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="circle"></div>
<script src="app.js"></script>
</body>
</html>

How can I simulate gravity or jump for a div using only html, css and javascript?

I'm doing a plataform game similar to Mario Bros I already have the left and right movement, but now I need to simulate a jump only using javascript, css and html i have this code right now
<div id="container">
<div id="roll"></div>
<div id="tube1" class="tube"></div>
<div id="tube2" class="tube"></div>
<div id="tube3" class="tube"></div>
<script>
var reqID, dir;
var left = 0;
var top = 0;
var player, tube, pw, ph, px, py, tw, th, tx, ty;
function detectCollisions() {
//Access the current location and dimension of both objects
for(let i = 0; i < tube.length; i++)
{
pw = player.offsetWidth;
ph = player.offsetHeight;
px = player.offsetLeft;
py = player.offsetTop;
tw = tube[i].offsetWidth;
th = tube[i].offsetHeight;
tx = tube[i].offsetLeft;
ty = tube[i].offsetTop;
console.log(tw);
//check to see if tube has intersected width player in any direction
if((px+pw) > tx && px < (tx+tw) && (py+ph) > ty && py < (ty+th)) {
//Do anything you want in the program when collision is detected
console.log("collision detected with" + tube[i].id);
this.player.style.left = (player.offsetLeft -= 3) + 'px';
/*document.body.removeChild(tube[i]);*/
}
}
window.requestAnimationFrame(detectCollisions);
}
function stopAnimation() {
console.log('stop');
/*window.cancelAnimationFrame(reqID);*/
player.style.animation = "face-forward 0.9s steps(4) infinite";
}
function move(e) {
console.log(e.keyCode)
//up
if(e.keyCode == 38) {
player.style.top = (player.offsetTop -= 3) + 'px';
} else if(e.keyCode == 39) { //right arrow
player.style.left = (player.offsetLeft += 3) + 'px';
player.style.animation = "walk-right 0.9s steps(4) infinite";
} else if(e.keyCode == 40) { //down arrow
player.style.top = (player.offsetTop += 3) + 'px';
} else if(e.keyCode == 37) { //left arrow
player.style.left = (player.offsetLeft -= 3) + 'px';
player.style.animation = "walk-left 0.9s steps(4) infinite";
}
/*reqID = window.requestAnimationFrame(startAnimation);*/
}
function createScenario() {
var positionLeft = 0;
for(let i = 0; i < 40; i++) {
let iDiv = document.createElement('div');
iDiv.id = 'floor' + i;
iDiv.className = 'floor';
iDiv.style.left = positionLeft + 'px';
iDiv.style.top = 170 + 'px';
document.getElementById('container').appendChild(iDiv);
positionLeft += 35;
}
/*let iDiv = document.createElement('div');
iDiv.id = "roll";
iDiv.style.zIndex = "5";
document.getElementByTagName('body').appendChild(iDiv);*/
}
/*Setting everything at the beggining*/
var spriteSheet = new Image();
spriteSheet.src = './resources/king_left_right.png';
function docReady() {
/*player = document.createElement("div");
player.id = "roll";
player.style.backgroundPosition = "background-position: 200px -5px;"
player.style.background = "url("+spriteSheet.src+")";
document.body.appendChild(player);*/
player = document.getElementById('roll');
player.style.backgroundPosition = "background-position: 200px -5px;"
player.style.background = "url("+spriteSheet.src+")";
tube = document.getElementsByClassName("tube");
detectCollisions();
createScenario();
}
document.onkeydown = move;
document.onkeyup = stopAnimation;
window.addEventListener("load", function(event) {
docReady();
});
</script>
Could you give me an approch please, of course my character must jump and return to the ground or on the tube in the code.
Any help will be appreciated...
I made this site Mindhive some time ago. If you click the hexagons they'll all drop but depending on how you click them they'll drop differently. You can fling them around with your mouse too.
I used Box2D which is a javascript physics engine that should give you all the tools you need to get something built in Javascript, html etc with realistic gravity and movement.
Hope that helps a bit
Try this..
https://www.w3schools.com/graphics/game_bouncing.asp
May give you basic idea.

Adobe Animate CC not drawing anything on publish/test. Java-issue? HTML5-canvast document

When I test or publish my project, which is a jigsaw puzzle from this tutorial: https://www.youtube.com/watch?v=uCQuUZs3UGE
Nothing gets drawn except the grey background. No puzzle pices nor any puzzle shape is drawn at all. I also get a warning:
WARNINGS:
Frame numbers in EaselJS start at 0 instead of 1. For example, this affects gotoAndStop and gotoAndPlay calls. (17)
But that should just be a warning, not an error. So might there be an error in my javascript code? This is the code, its fairly simple:
//************
// Initialize;
var numPieces = 16;
for (var i = 0; i = < numPieces; i++)
{
var pieceName = "p" + (i + 1);
var piece = this[pieceName];
if (piece)
{
piece.name = pieceName;
piece.on("mousedown", function(evt)
{
this.scaleX = 1;
this.scaleY = 1;
this.shadow = null;
this.parent.addChild(this);
this.offset = (x:this.x - evt.stageX, y:this.y - evt.stageY);
});
piece.on("pressmove", function (evt)
{
this.x = evt.stageX + this.offset.x;
this.y = evt.stageY + this.offset.y;
});
piece.on("pressup", function(evt)
{
var target = this.parent["t"+this.name.substr(1)];
if (target && hitTestInRange(target, 30) )
{
this.x = target.x;
this.y = target.y;
}
});
}
}
function hitTestInRange( target, range )
{
if (target.x > stage.mouseX - range &&
target.x < stage.mouseX + range &&
target.y > stage.mouseY - range &&
target.y < stage.mouseY + range)
{
return true;
}
return false;
}
I also included a screenshot of the project. screenshot
Thanks in advance

Not moving through array of Objects?

I have been making a game, my problem is when you click the space key it shoots 1 bullet, but when you do it again nothing happens. I have made it so the game starts with 30 bullets, and they are stored at the top left of screen out of view. When space is clicked they get fired from the tip of your ship using its X, Y values.
Click here to see what I mean:
http://www.taffatech.com/DarkOrbit.html
- as you can see only 1 fires, ever.
Here is the bullet object
function Bullet() //space weapon uses this
{
this.srcX = 0;
this.srcY = 1240;
this.drawX = -20;
this.drawY = 0;
this.width = 11;
this.height = 4;
this.bulletSpeed = 3;
this.bulletReset = -20;
}
Bullet.prototype.draw = function()
{
this.drawX += this.bulletSpeed;
ctxPlayer.drawImage(spriteImage,this.srcX,this.srcY,this.width,this.height,this.drawX,this.drawY,this.width,this.height);
if (this.drawX > canvasWidth)
{
this.drawX = this.bulletReset;
}
}
Bullet.prototype.fire = function(startX, startY)
{
this.drawX = startX;
this.drawY = startY;
}
This is the player Object: (the ship)
function Player() //Object
{
//////Your ships values
this.PlayerHullMax = 1000;
this.PlayerHull = 1000;
this.PlayerShieldMax = 1000;
this.PlayerShield = 347;
this.SpaceCrystal = 2684;
this.Speed = 5; //should be around 2 pixels every-time draw is called by interval, directly linked to the fps global variable
////////////
///////////flags
this.isUpKey = false;
this.isDownKey = false;
this.isLeftKey = false;
this.isRightKey = false;
////////space Weapon
this.noseX = this.drawX + 100;
this.noseY = this.drawY + 30;
this.isSpaceBar = false;
this.isShooting = false;
this.bullets = [];
this.currentBullet = 0;
this.bulletAmount = 30;
for(var i = 0; i < this.bulletAmount; i++) //
{
this.bullets[this.bullets.length] = new Bullet();
}
/////////////
////Pick Ship
this.type = "Cruiser";
this.srcX = PlayerSrcXPicker(this.type);
this.srcY = PlayerSrcYPicker(this.type);
this.drawX = PlayerdrawXPicker(this.type);
this.drawY = PlayerdrawYPicker(this.type);
this.playerWidth = PlayerWidthPicker(this.type);
this.playerHeight = PlayerHeightPicker(this.type);
////
}
Player.prototype.draw = function()
{
ClearPlayerCanvas();
ctxPlayer.globalAlpha=1;
this.checkDirection(); //must before draw pic to canvas because you have new coords now from the click
this.noseX = this.drawX + (this.playerWidth-10);
this.noseY = this.drawY + (this.playerHeight/2);
this.checkShooting();
this.drawAllBullets();
ctxPlayer.drawImage(spriteImage,this.srcX,this.srcY,this.playerWidth,this.playerHeight,this.drawX,this.drawY,this.playerWidth,this.playerHeight);
};
Player.prototype.drawAllBullets = function()
{
for(var i = 0; i < this.bullets.length; i++)
{
if(this.bullets[i].drawX >= 0)
{
this.bullets[i].draw();
}
}
}
Player.prototype.checkShooting = function()
{
if(this.isSpaceBar == true && this.isShooting == false)
{
this.isShooting = true;
this.bullets[this.currentBullet].fire(this.noseX, this.noseY);
this.currentBullet++;
if(this.currentBullet >= this.bullets.length)
{
this.currentBullet = 0;
}
else if(this.isSpaceBar == false)
{
this.isShooting = false;
}
}
}
This is in a method that checks what keys are down:
if (KeyID === 32 ) //spacebar
{
Player1.isSpaceBar = true;
e.preventDefault(); //webpage dont scroll when playing
}
This is in a method that checks what keys are up:
if (KeyID === 32 ) //left and a keyboard buttons
{
Player1.isSpaceBar = false;
e.preventDefault(); //webpage dont scroll when playing
}
Any other info you need just ask!
Okay, I think I figured it out
try adding isShooting false to the key up event
if (KeyID === 32 ) //left and a keyboard buttons
{
Player1.isSpaceBar = false;
Player1.isShooting = false;
e.preventDefault(); //webpage dont scroll when playing
}

Categories