Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

265
Views
Why is my collision code not working at all?

I am relatively new to JavaScript, and am looking to create a platformer game for a class project. I have tried multiple ways to make a player rectangle collide with an obstacle rectangle but none have worked the way I intended. This method that I wrote myself is not functioning at all, and I have no clue why.

var ctx = myCanvas.getContext("2d");

var fps = 50
var level = 1
var gravity = 0.5

var player = {
  x: 0,
  y: 0,
  x_v: 0,
  y_v: 0,
  width: 20,
  height: 20,
  speed: 3,
  jump: 10,
  color: "blue"
}

const obstacle = {
  x: 0,
  y: 550,
  width: 600,
  height: 100,
  color: "black"
}

function MyKeyUpHandler(MyEvent) {
  if (MyEvent.keyCode == 37 || MyEvent.keyCode == 39) {
    player.x_v = 0
  }; // not left or right
  if (MyEvent.keyCode == 38 || MyEvent.keyCode == 40) {
    player.y_v = 0
  }; // not up or down
}


function MyKeyDownHandler(MyEvent) {
  if (MyEvent.keyCode == 37) {
    player.x_v = -player.speed
  }; // left
  if (MyEvent.keyCode == 38) {
    player.y_v = -player.jump
  }; // up
  if (MyEvent.keyCode == 39) {
    player.x_v = player.speed
  }; // right
  MyEvent.preventDefault();
}

function renderplayer() {
  player.y_v = player.y_v + gravity
  player.x = player.x + player.x_v
  player.y = player.y + player.y_v
  ctx.fillStyle = player.color
  ctx.fillRect(player.x, player.y, player.width, player.height)
}

function renderobstacle() {
  ctx.fillStyle = obstacle.color
  ctx.fillRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height)
}

function collision() {
  if (player.y == obstacle.y - player.height) {
    player.y_v = 0
  }
}


function frameyshit() {
  ctx.clearRect(0, 0, 600, 600)
  renderplayer();
  renderobstacle();
  collision();
  if (player.y >= 600) {
    player.y = 1
    player.x = 1
    player.y_v = 0
  }
}

setInterval(frameyshit, 1000 / fps)
addEventListener("keydown", MyKeyDownHandler)
addEventListener("keyup", MyKeyUpHandler)
<canvas id=myCanvas width=600 height=600 style="background-color: transparent;"> </canvas>

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!