Prototype function calling an object undefined - javascript

I am trying to make a collision function for my new platformer game and I came across an error when making my collision prototype function.
platforms = [];
var newPlatform = function(x, y) {
this.x = x,
this.y = y,
this.width = 50,
this.height
}
var platform1 = new newPlatform(10, 100);
var platform2 = new newPlatform(50, 50);
platforms.push(platform1);
platforms.push(platform2);
var player = {
x:100,
y:305,
width:80,
height:120,
velocity_y:4
}
platforms.prototype.collision = function(player) {
return (this.x < player.x + player.width && this.x + this.width > player.x && this.y
< player.y + player.height && this.y + this.height > player.y);
}
for (let i = 0; i < platforms.length; i++) {
if (platforms[i].collision(player)) {
player.velocity_y = 0 ;
}
}
This gives out an error that reads "Cannot set property 'collision' of undefined" does anyone know how to fix this?

Related

Refers to a global variable while encapsulated one is available

In case below "player" referring to global variables, that breaks OOP principle of encapsulation. Whatever I need from the global scope pass to the class instance via constructor. How can I did it?
If I create parent variable (some Character), than code will not work. Maybe this is a nube question, but I don't know, how it works.
p.s. - when I take "player" in "Enemy" thought "this", all construction breaks down.
var Enemy = function(x, y, speed, player) {
this.x = x;
this.y = y;
this.speed = speed;
this.sprite = 'images/enemy-bug.png';
this.player = player;
};
Enemy.prototype.update = function(dt) {
this.x += +(this.speed * dt);
if (this.x > canvasWidth) {
this.x = borgSpawn;
this.speed = Math.floor(100 + Math.random() * 200);
}
if (
player.x > this.x - enemySize &&
player.x < this.x + enemySize &&
player.y > this.y - enemySize &&
player.y < this.y + enemySize
) {
player.x = playerSpawnX;
player.y = playerSpawnY;
}
};
Enemy.prototype.render = function() {
ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};
var enemyLocation = [60, 140, 220];
var allEnemies = enemyLocation.map(y => new Enemy(0, y, 300, player));
var Player = function(x, y) {
this.x = x;
this.y = y;
this.sprite = 'images/char-boy.png';
};
Player.prototype.update = function() {
if (this.y < 60) {
this.x = playerSpawnX;
this.y = playerSpawnY;
}
};
Player.prototype.render = function() {
ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};
Player.prototype.handleInput = function(key) {
if (key === 'left' && this.x > 0) {
this.x = this.x - horizontalStep;
} else if (key === 'right' && this.x != stepZone) {
this.x = this.x + horizontalStep;
} else if (key === 'up') {
this.y = this.y - verticalStep;
} else if (key === 'down' && this.y != stepZone) {
this.y = this.y + verticalStep;
}
};
var player = new Player(playerSpawnX, playerSpawnY);
document.addEventListener('keyup', function(e) {
var allowedKeys = {
37: 'left',
38: 'up',
39: 'right',
40: 'down'
};
player.handleInput(allowedKeys[e.keyCode]);
});
No need to pass "player" parameter to "enemy" object. Your Enemy.prototype.update function will work fine without this reference.

2d collision checking javascript, doesen't work properly

I've been experementing with 2d rectangular collision but i stumbled into an error i can't fix, even after over an hour of tweaking.
Collision works fine up, down and left. but the right causes the player to go up to the y value of the collision. The code is the exact same as the left site (correctly mirrored. I think)
var player = new Player(50,50,100,0.3,false,0,0)
var playerCollision = new Collision(player.x,player.y,64,64);
var ground = new Collision(0,500,300,100);
var wall = new Collision(200,400,100,100);
var wall2 = new Collision(0,400,100,100);
var collisions = [ground,wall,wall2];
for (i=0;i<collisions.length;i++) {
if (collisions[i].checkCollision(playerCollision)) {
if (collisions[i].x - playerCollision.x > 0 && playerCollision.x + playerCollision.width > collisions[i].x-1 && playerCollision.y+playerCollision.height-20 > collisions[i].y) {
player.dx = 0;
player.x = collisions[i].x-64;
} else if ((collisions[i].x + collisions[i].width)- playerCollision.x < 0 && playerCollision.x < collisions[i].x+collisions[i].width+1 && playerCollision.y+playerCollision.height-20 > collisions[i].y) {
player.dx = 0;
player.x = collisions[i].x+collisions[i].width;
} else if (collisions[i].y - playerCollision.y+playerCollision.height > 0) {
player.dy = 0;
player.y = collisions[i].y-64;
} else if ((collisions[i].y+collisions[i].height) - playerCollision.y < 0) {
player.dy = 0;
player.y = collisions[i].y+collisions[i].height;
}
}
}
Collision.js:
function Collision(x,y,width,height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.checkCollision = function(other) {
if (this.x < other.x + other.width &&
this.x + this.width > other.x &&
this.y < other.y + other.height &&
this.height + this.y > other.y) {
return true
} else {
return false;
}
}
this.show = function() {
ctx.strokeStyle = "#38ff35";
ctx.strokeRect(this.x,this.y,this.width,this.height);
}
}
EDIT:
changed some code (didn't fix the problem tho)
obj1
position = (0, 0)
dimensions = (2, 0)
obj2
position = (2, 0)
dimensions = (2, 0)
0 < 2 + 2 = true
0 + 2 > 2 = false
this already shows that your check doesn't mathematically make sense. These two blocks should be overlapping but return false
Try:
if (this.x + this.width < other.x - other.width ||
this.x - this.width > other.y + other.width ||
this.y + this.height < other.y - other.height ||
this.y - this.height > other.y + other.height)
{
no collisions
}

how can I detect collision in a 2D tile game map

I made this basic game where I drew a map and a player, the player can move anywhere but how can I make so that it wont move when its on the tile[1] in the map?
also when I try to check if the player.x is greater than 50 it could go left it works but than if I click 2 keys at once it goes through
const context = document.querySelector("canvas").getContext("2d");
var rgb = 'rgb(' + Math.random()*256 + ',' + Math.random()*256 + ',' + Math.random()*256 + ','+Math.random() + ')';
document.onload = Loop();
var width = 1500;
var height = 800;
function Loop(){
var width = 1500;
var height = 800;
context.canvas.height = height;
context.canvas.width = width;
this.interval = setInterval(Update, 1000/100);
}
const Player = function(x, y, w, h, color) {
this.x = x; this.y = y; this.w = w; this.h = h;
this.speedY = 0; this.speedX = 0;
this.Draw = function(){
context.fillStyle = this.color;
context.fillRect(this.x, this.y, this.w, this.h);
};
this.Move = function(){
this.x += this.speedX;
this.y += this.speedY;
};
};<code>
var player = new Player(100,100,50, 50, rgb);
var Key = {};
function Update(){
context.clearRect(0, 0, width, height);
Map();
player.Draw();
player.Move();
onkeydown = onkeyup = function(e){
player.speedX = 0;
player.speedY = 0;
e = e || event;
Key[e.keyCode] = e.type == 'keydown';
if(Key[37] || Key[65]) {player.speedX -= 2}
if(Key[38] || Key[87]) {player.speedY -= 2}
if(Key[39] || Key[68]) {player.speedX += 2}
if(Key[40] || Key[83]) {player.speedY += 2}
if(Key[32]) {player.color = 'rgb(' + Math.random()*256 + ',' + Math.random()*256 + ',' + Math.random()*256 + ','+Math.random()*1 + ')';}
};
}
var map = [
1, 1, 1, 1, 1,
1, 0, 0, 0, 1,
1, 0, 0, 0, 1,
1, 0, 0, 0, 1,
1, 1, 1, 1, 1
];
var row = 5;
var column = 5;
function Map(){
for(let y = -1; y < column; y++){
for(let x = -1; x < row; x++){
switch(map[((y*row) + x)]) {
case 0: context.fillStyle = player.color;
break;
case 1: context.fillStyle = "#ffffff";
break;
default: context.fillStyle = "#000000";
}
context.fillRect(x*50, y*50, 50, 50);
}
}
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
display: block;
margin: auto;
border: solid 1px white;
border-radius: 10px;
}
script {
display: none;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
void function() {
"use strict";
// Classes
function Camera(x,y) {
this.x = x || 0.0;
this.y = y || 0.0;
}
Camera.prototype = {
set: function(x,y) {
this.x = x || 0.0;
this.y = y || 0.0;
},
pan: function(x,y) {
this.x += x || 0.0;
this.y += y || 0.0;
}
};
var nextID = 0;
function Tile(colour) {
this.id = nextID++;
this.colour = colour || "black";
}
function Map(width,height) {
this.width = width || 1;
this.height = height || 1;
this.map = [];
this.map.length = this.height;
for (var y = 0; y < this.height; ++y) {
this.map[y] = [];
this.map[y].length = width;
for (var x = 0; x < this.width; ++x) {
this.map[y][x] = Math.random() < 0.2 ?
this.TILE_WALL:
this.TILE_GRASS;
}
this.map[y][0] = this.TILE_WALL;
this.map[y][this.width - 1] = this.TILE_WALL;
}
for (var x = 0; x < this.width; ++x) {
this.map[0][x] = this.TILE_WALL;
this.map[this.height - 1][x] = this.TILE_WALL;
}
}
Map.prototype = {
TILE_WIDTH: 32.0,
TILE_HEIGHT: 32.0,
INV_TILE_WIDTH: 0.0,
INV_TILE_HEIGHT: 0.0,
TILE_AIR: new Tile("#00000000"),
TILE_GRASS: new Tile("#00AA00FF"),
TILE_WALL: new Tile("#555555FF"),
set: function(x,y,tile) {
this.map[y][x] = tile;
},
scaleX: function(x) {
return (x * this.INV_TILE_WIDTH) | 0;
},
scaleY: function(y) {
return (y * this.INV_TILE_HEIGHT) | 0;
},
isColliding: function(x,y) {
return x > -1 && x < this.width
&& y > -1 && y < this.height
&& this.map[y][x].id > 1;
},
render: function(ctx,camera) {
for (var y = 0; y < this.height; ++y) {
for (var x = 0; x < this.width; ++x) {
var tile = this.map[y][x];
var _x = x * this.TILE_WIDTH - camera.x;
var _y = y * this.TILE_HEIGHT - camera.y;
ctx.fillStyle = tile.colour;
ctx.fillRect(_x,_y,this.TILE_WIDTH - 1,this.TILE_HEIGHT - 1);
}
}
}
};
Map.prototype.INV_TILE_WIDTH = 1.0 / Map.prototype.TILE_WIDTH;
Map.prototype.INV_TILE_HEIGHT = 1.0 / Map.prototype.TILE_HEIGHT;
function Player(x,y) {
this.x = x || 0.0;
this.y = y || 0.0;
this.dx = 0.0;
this.dy = 0.0;
this.isUp = false;
this.isDown = false;
this.isLeft = false;
this.isRight = false;
}
Player.prototype = {
WIDTH: 20.0,
HEIGHT: 20.0,
ACCELERATION: 1.0,
DEACCELERATION: 0.5,
MAX_SPEED: 3.0,
tick: function(map) {
// Movement
if (this.isUp) {
this.dy -= this.ACCELERATION;
if (this.dy < -this.MAX_SPEED) {
this.dy = -this.MAX_SPEED;
}
} else if (this.dy < 0.0) {
this.dy += this.DEACCELERATION;
if (this.dy > 0.0) {
this.dy = 0.0;
}
}
if (this.isDown) {
this.dy += this.ACCELERATION;
if (this.dy > this.MAX_SPEED) {
this.dy = this.MAX_SPEED;
}
} else if (this.dy > 0.0) {
this.dy -= this.DEACCELERATION;
if (this.dy < 0.0) {
this.dy = 0.0;
}
}
if (this.isLeft) {
this.dx -= this.ACCELERATION;
if (this.dx < -this.MAX_SPEED) {
this.dx = -this.MAX_SPEED;
}
} else if (this.dx < 0.0) {
this.dx += this.DEACCELERATION;
if (this.dx > 0.0) {
this.dx = 0.0;
}
}
if (this.isRight) {
this.dx += this.ACCELERATION;
if (this.dx > this.MAX_SPEED) {
this.dx = this.MAX_SPEED;
}
} else if (this.dx > 0.0) {
this.dx -= this.DEACCELERATION;
if (this.dx < 0.0) {
this.dx = 0.0;
}
}
// Collision
if (this.dx !== 0.0) {
var minY = map.scaleY(this.y);
var maxY = map.scaleY(this.y + this.HEIGHT);
var minX = 0;
var maxX = 0;
if (this.dx < 0.0) {
minX = map.scaleX(this.x + this.dx);
maxX = map.scaleX(this.x);
} else {
minX = map.scaleX(this.x + this.WIDTH);
maxX = map.scaleX(this.x + this.WIDTH + this.dx);
}
loop:
for (var y = minY; y <= maxY; ++y) {
for (var x = minX; x <= maxX; ++x) {
if (map.isColliding(x,y)) {
this.x = this.dx < 0.0 ?
(x + 1) * map.TILE_WIDTH:
x * map.TILE_WIDTH - this.WIDTH - 1;
this.dx = 0.0;
break loop;
}
}
}
}
if (this.dy !== 0.0) {
var minX = map.scaleX(this.x);
var maxX = map.scaleX(this.x + this.WIDTH);
var minY = 0;
var maxY = 0;
if (this.dy < 0.0) {
minY = map.scaleY(this.y + this.dy);
maxY = map.scaleY(this.y);
} else {
minY = map.scaleY(this.y + this.HEIGHT);
maxY = map.scaleY(this.y + this.HEIGHT + this.dy);
}
loop:
for (var y = minY; y <= maxY; ++y) {
for (var x = minX; x <= maxX; ++x) {
if (map.isColliding(x,y)) {
this.y = this.dy < 0.0 ?
(y + 1) * map.TILE_HEIGHT:
y * map.TILE_HEIGHT - this.HEIGHT - 1;
this.dy = 0.0;
break loop;
}
}
}
}
this.x += this.dx;
this.y += this.dy;
},
render: function(ctx,camera) {
camera.set(this.x,this.y);
ctx.lineWidth = 1;
ctx.strokeStyle = "black";
ctx.fillStyle = "darkred";
ctx.beginPath();
ctx.rect(this.x - camera.x,this.y - camera.y,this.WIDTH,this.HEIGHT);
ctx.fill();
ctx.stroke();
}
};
// Variables
var canvasWidth = 180;
var canvasHeight = 160;
var canvas = null;
var ctx = null;
var camera = null;
var map = null;
var player = null;
// Functions
function onKeyDown(e) {
switch(e.key.toUpperCase()) {
case "W": player.isUp = true; break;
case "S": player.isDown = true; break;
case "A": player.isLeft = true; break;
case "D": player.isRight = true; break;
}
}
function onKeyUp(e) {
switch(e.key.toUpperCase()) {
case "W": player.isUp = false; break;
case "S": player.isDown = false; break;
case "A": player.isLeft = false; break;
case "D": player.isRight = false; break;
}
}
function loop() {
// Tick
player.tick(map);
// Render
ctx.fillStyle = "gray";
ctx.fillRect(-canvasWidth >> 1,-canvasHeight >> 1,canvasWidth,canvasHeight);
map.render(ctx,camera);
player.render(ctx,camera);
//
requestAnimationFrame(loop);
}
// Entry point (first to execute)
onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx = canvas.getContext("2d");
ctx.translate(canvasWidth >> 1,canvasHeight >> 1);
camera = new Camera(0.0,0.0);
map = new Map(10,10);
player = new Player(40.0,40.0);
map.set(1,1,map.TILE_GRASS);
addEventListener("keydown",onKeyDown);
addEventListener("keyup",onKeyUp);
loop();
}
}();
</script>
</body>
</html>
Firstly, looking at your code, there are some things that are missing which is required to implement basic collision detection and those are:
The player's current direction that he/she is moving in. This is important because it allows the function determining the collision detection to distinguish which side it is checking for the collision (Up, down, left, or right) since a player can only collide with one side at a time.
The tile's position and size. This is also very important because like the first point, there is only one side of the tile that the player can collide with and knowing the size and position can determine if it is a collision or not based on the players size and position.
Also, since you mentioned it is a basic game, the implementation below is a basic collision detection. If you were to make a more complex and bigger game, you should try looking into quad trees for more efficient collision detection:
https://gamedevelopment.tutsplus.com/tutorials/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space--gamedev-374
Now this is the function for detecting collision, for the sake of readability and shortness, p will represent the player object and t would represent the tile object. This function returns whether or not the player is colliding with a tile based on their direction of movement.
function isColliding(p, t){
if (p.direction == 'up') {
return p.y +(p.height/2)-p.speedY< t.y + t.height && p.y > t.y
&& p.x + p.width > t.x && p.x < t.x + t.width;
}
if (p.direction == 'down') {
return p.y + (p.height/2)+p.speedY > t.y && p.y < t.y
&& p.x + p.width > t.x && p.x < t.x + t.width;
}
if (p.direction == 'right') {
return p.x + p.width+p.speedX > t.x && p.x < t.x
&& p.y +(p.height/2)> t.y && p.y + p.height < t.y +t.height+ (p.height / 2);
}
if (p.direction == 'left') {
return p.x -p.speedX< t.x + t.width && p.x > t.x
&& p.y +(p.height/2)> t.y && p.y + p.height < t.y +t.height+ (p.height / 2);
}
return false;
}
You would probably want to put this in the player move function to constantly detect for tiles as it is moving. To do that, you'd want to modify your keydown detection so that with each different keydown, it would update the player's direction, here's a simple example:
document.onkeydown = function(event){
if (event.keyCode == 87)
player.up = true;
else if (event.keyCode == 65)
player.left = true;
else if (event.keyCode == 83)
player.down = true;
else if (event.keyCode == 68)
player.right = true;
}
and another simple example for every time the player moves (user presses a keydown):
const Player= function(/*Param stuff*/){
/*Property stuff*/
//tileArray is the array (or object, your choice) of all the current tiles in the map
this.move=function(tileArray){
//Go through all tiles to see if player is colliding with any of them
for(var t in tileArray){
if(this.up){
if(isColliding(this, tileArray[t]){
//functionality for when player collides
}else{
//functionality for when player doesn't collide
}
}
//check if player is going down, left, etc
}
}
}
These are just examples of how to implement the detection. You should use it as a reference to implement it relatively to how your code function because I didn't write it based on what you posted.
PS.
Make sure to also convert the directions to false after the user stops pressing the key.

Collison not working

I tried to do a collision prototype for my gem object and every time my player interacts with it, it doesn't reset. Dev tools isn't coming up with any errors as well.
var checkCollisions = function(targets){
var target;
if (Array.isArray(targets)){
for (var i =0; i < targets.length; i++){
target = targets[i];
if (targets === allEnemies){
target.width = 50;
target.height = 40;
}
if (player.x < target.x + target.width && player.x + player.width > target.x && player.y < target.y + target.height && player.y + player.height > target.y){
console.count('collision');
player.reset();
return true;
}
}
}
return false;
};
var Gem = function(x,y){
this.x = [2,275,300];
this.y = [200,150,80];
this.width = 50;
this.height = 40;
this.sprite = 'images/gem-blue.png';
}
Gem.prototype.update = function(){
this.x = 200
this.y = 200
};
Gem.prototype.render = function() {
ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};
Gem.prototype.reset = function(){
this.x = 0;
this.y = 0;
};
Gem.prototype.checkCollision = function(player) {
for(var i = 0; i player.length; i++){
if(player.x < this.x + this.width &&
player.x + player.width > this.x &&
player.y < this.y + this.height &&
player.height + player.y > this.y);
}
console.log("got a gem!");
gem.reset();
};
var gem = new Gem();

HTML5 Canvas: Drawing shapes around edges of the canvas

I'm creating a basic game that draws squares at random positions on a canvas, but sometimes the shape gets cut off because it's outside of the canvas' boundaries. Can any one explain how I could go about getting the square to be drawn on the other side of the canvas (similar to how it's done in asteroids)? The searches I've come up with haven't been helpful. Any help is appreciated.
OK I think I've solved this one. Basically this code only draws the square whilst it is inside the canvas, if it leaves the canvas it checks which boundaries it is leaving and updates the position. The looped variable is needed because otherwise the square will be always leaving the canvas.
var canvas = document.getElementById('bg');
var ctx = canvas.getContext('2d');
var squares = [];
squares[squares.length] = new Square(200, 200, 20, 'red', 0.785398164);
function Square(x, y, size, colour, angle)
{
this.x = x;
this.y = y;
this.size = size;
this.colour = colour;
this.speed = 5;
this.angle = angle;
this.looped = false;
}
Square.prototype.update = function()
{
this.x += (Math.cos(this.angle) * this.speed);
this.y += (Math.sin(this.angle) * this.speed);
if (this.x < canvas.width && this.x + this.size > 0 &&
this.y < canvas.height && this.y + this.size > 0)
{
this.draw();
this.looped = false;
}
else
{
if (this.x > canvas.width && !this.looped)
{
this.x = -this.size;
}
if (this.x + this.size < 0 && !this.looped)
{
this.x = this.size + canvas.width;
}
if (this.y > canvas.height && !this.looped)
{
this.y = -this.size;
}
if (this.y + this.size < 0 && !this.looped)
{
this.y = this.size + canvas.height;
}
this.looped = true;
}
}
Square.prototype.draw = function()
{
ctx.fillStyle = this.colour;
ctx.fillRect(this.x, this.y, this.size, this.size);
}
function gameLoop()
{
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < squares.length; i++)
{
squares[i].update();
}
requestAnimationFrame(gameLoop);
}
gameLoop();
(function()
{
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x)
{
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element)
{
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function()
{
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id)
{
clearTimeout(id);
};
}());
I'd do a JSFiddle but requestAnimationFrame doesn't play nice with it.

Categories

Resources