2017-08-10 83 views
0
<!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> 

我无法使精灵与 画布的墙壁碰撞。使用画布进行精灵碰撞检测Javascript

sprite已经通过css动画,但它总是逃离画布墙壁。我已经做了一些关于碰撞检测的研究,大多数代码包括设置对象的x和y位置,并添加if语句以检查它是否触及画布墙,但我无法理解如何在该sprite上实现该代码。任何人,请善举举一个例子。

我对javascript仍然陌生,并且已经在这里呆了几个星期。

+0

你能创建演示吗?您可以使用jsfiddle,codepen或堆栈片段。谢谢 – sol

+0

@ovokuro通过演示你的意思是喜欢看代码的工作方式? –

回答

0

如果您在移动时达到极限,只需将其移回即可?

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

在右侧函数比较精灵左侧位置+精灵宽度与画布宽度。