xxxxxxxxxx
159
/* 11/18/24 progress
collision dectection
Taylor Ith
*/
let player = Player();
let ninjastar;
let collisionRadius = 50;
// global variable to contain image data
//accessed by preload and draw
let charIdleSprite, charWalkSprite, char2HealthSprite;
let ninjastar1move;
let backgroundMusic;
function preload() {
charIdleSprite = loadImage("Sprite/character_Idle.gif");
charWalkSprite = loadImage("Sprite/character_walk.gif");
char2HealthSprite = loadImage("Sprite/sprite_2hp.gif");
ninjastar1move = loadImage("Sprite/NinjaStar2x0.gif");
backgroundMusic = loadSound(
"audio/oga_japanese_hacks-[AudioTrimmer.com].mp3"
);
}
function setup() {
createCanvas(400, 400);
imageMode(CENTER);
ninjastar = Ninjastar();
backgroundMusic.play();
backgroundMusic.loop(true);
}
function draw() {
background(220);
player.move();
player.display();
ninjastar.move();
ninjastar.display();
let ninjacollide = detectCollision(player, ninjastar);
if (ninjacollide) {
player.hit();
}
}
function Player() {
let x = 200;
let y = 200;
let animationState = 0;
// 1 = move
// 0 = idle
// 2 = 2hp
function move() {
if (animationState != 2) {
animationState = 0;
}
if (keyIsDown(RIGHT_ARROW)) {
x = x + 5;
animationState = 1; //walk animation
}
if (keyIsDown(LEFT_ARROW)) {
x = x - 5;
animationState = 1; //walk animation
}
if (keyIsDown(UP_ARROW)) {
y = y - 5;
animationState = 1;
}
if (keyIsDown(DOWN_ARROW)) {
y = y + 5;
animationState = 1;
}
}
function display() {
if (animationState == 0) {
image(charIdleSprite, x, y);
} else if (animationState == 1) {
image(charWalkSprite, x, y);
} else if (animationState == 2) {
image(char2HealthSprite, x, y);
}
}
function getPosition() {
return { x, y };
}
function hit() {
animationState = 2;
}
return { move, display, getPosition, hit };
}
function Ninjastar() {
let x = random(0, 500);
let y = random(0, 500);
let animationState = 0;
function move() {
x = x + 7;
if (x > width) {
x = 0;
}
y = y + 5;
if (y > width) {
y = 0;
}
}
function display() {
if (animationState == 0) {
image(ninjastar1move, x, y);
}
}
function getPosition() {
return { x, y };
}
return { move, display, getPosition };
}
//compare the position of two objects
// return true if they are colliding
function detectCollision(objA, objB) {
let aPosition = objA.getPosition();
let bPosition = objB.getPosition();
let d = dist(aPosition.x, aPosition.y, bPosition.x, bPosition.y);
let isColliding = d < collisionRadius;
return isColliding; // returns true or false
}
function mousePressed() {}