A
A
Afafks1231321321652020-03-04 14:20:21
JavaScript
Afafks123132132165, 2020-03-04 14:20:21

How to make a collision of a ray and an object?

How can I make a collision of a ray and an object?

<!DOCTYPE html>
<html>
<head>
  <title>Game</title>
</head>
<body>
<canvas id = "canvas" width = "320" height = "480"></canvas>
<script type="text/javascript">
document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var x = 160;
var y = 240;
var left = 0;
var right = 0;

var rays = [];
var blocks = [];

for(i = 0;i < 100;i++){
  rays.push({lx:0,ly:0,angle:i});
}

blocks.push({x:x+64,y:y});

document.addEventListener("keydown",function(e){
  if(e.keyCode == 65){
    left = 1;
  }

  if(e.keyCode == 68){
    right = 1;
  }
});

document.addEventListener("keyup",function(e){
  if(e.keyCode == 65){
    left = 0;
  }

  if(e.keyCode == 68){
    right = 0;
  }
});

function game(){
  ctx.clearRect(0,0,320,480);

  ctx.fillStyle = "black";

  ctx.fillRect(x,y,32,32);

  for(i in blocks){
    ctx.fillStyle = "purple";
    ctx.fillRect(blocks[i].x,blocks[i].y,32,32);
  }

  for(i in rays){
    rays[i].lx = Math.cos((rays[i].angle/180) * Math.PI)*100 + x + 16;
    rays[i].ly = Math.sin((rays[i].angle/180) * Math.PI)*100 + y + 16;

    ctx.beginPath();
    ctx.moveTo(x + 16,y + 16);
    ctx.lineTo(rays[i].lx,rays[i].ly);
    ctx.stroke();
    ctx.closePath();

    if(left == 1){
      rays[i].angle-=2;
    }

    if(right == 1){
      rays[i].angle+=2;
    }
  }

  ctx.beginPath();
  ctx.fillStyle = "red";
  ctx.arc(x+16,y+16,100,0,2*Math.PI);
  ctx.stroke();
  ctx.closePath();
}

setInterval(game,20);
</script>
</body>
</html>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2020-03-04
@Seasle

Watch until you're blue in the face:
Line Intersections Part I
Line Intersections Part II
Line Intersections Part III

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question