繁体   English   中英

用canvas Javascript碰撞精灵

[英]Collision detection of sprite with canvas Javascript

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>JavaScript</title>
<meta name="description" content="page description">
<meta name="author" content="discoveryvip">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/ptc.css">
<canvas id= "canvas" style= "border:1px solid; position:absolute; ">
</canvas>

<div id="sprite"></div>

<style>
#sprite {
width: 135px;
height: 100px;
background-image: url("images/spritesheet.png");
position:absolute;
bottom:1000px;
left:220px;
transition: all 2s;

animation: run 1s steps(5) infinite, slide 4s steps(100) infinite;
margin-right : 100%;

}

@keyframes run {
100% { background-position: -700px;}
}

@keyframes slide {
100% { margin-right: 135px;}

@keyframes slide {
100% { margin-left: -140px;
}

</style>

<script>
var sprite = document.getElementById("sprite");
var canvas = document.querySelector("canvas");
var ctx= canvas.getContext("2d");

sprite.style.top = 30 + "px" ;
sprite.style.left = 140 + "px";
sprite.style.height = 100 + "px";
sprite.style.width = 1067 ;
sprite.style.height = 640 ;

document.body.onkeyup = function() {
var e = event.keyCode,
charTop = parseInt(sprite.style.top),
charLeft = parseInt(sprite.style.left);
if (e == 40) { //down function
sprite.style.top = (parseInt(sprite.style.top)) + 20 + "px";
} else if (e == 37) { //left function
sprite.style.left = (parseInt(sprite.style.left)) - 20 + "px";
} else if (e == 39) { //right function
sprite.style.left = (parseInt(sprite.style.left)) + 20 + "px";
} else if (e == 38) { //up function
sprite.style.top = (parseInt(sprite.style.top)) - 20 + "px";

}
}

</script>

我无法使精灵与画布的墙壁碰撞。

该精灵已通过css进行了动画处理,但始终会从画布墙中逸出。 我已经对碰撞检测进行了一些研究,大多数代码包括设置对象的x和y位置以及放入if语句以检查它是否接触到画布壁,但是我不明白如何在该Sprite上实现该代码。任何人都请善待举一个例子。

我对javascript还是陌生的,已经参加了数周。

如果您在移动时达到极限,将其移回去怎么样?

} else if (e == 37) { 
  //left function
  sprite.style.left = (parseInt(sprite.style.left)) - 20 + "px";
  if(sprite.style.left < 0) 
  {
     sprite.style.left + 20;
  }
}

在右侧功能上,将子画面左侧位置+子画面宽度与画布宽度进行比较。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM