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仍然陌生,並且已經在這裏呆了幾個星期。
你能創建演示嗎?您可以使用jsfiddle,codepen或堆棧片段。謝謝 – sol
@ovokuro通過演示你的意思是喜歡看代碼的工作方式? –