一个简单的javascript小球碰撞代码
一个简单的javascript小球碰撞代码,综合了键盘操作,canvas等知识了,javascript入门小游戏基础
<body> <canvas id="canvas" width="400" height="400"></canvas> <script src="https://code.jquery.com/jquery-2.1.0.js"></script> <script> var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var width = canvas.width; var height = canvas.height; var circle = function (x, y, radius, fillCircle) { ctx.beginPath(); ctx.arc(x, y, radius, 0, Math.PI * 2, false); if (fillCircle) { ctx.fill(); } else { ctx.stroke(); } }; // The Ball constructor var Ball = function () { this.x = width / 2; this.y = height / 2; this.xSpeed = 5; this.ySpeed = 0; }; Ball.prototype.move = function () { this.x += this.xSpeed; this.y += this.ySpeed; if (this.x < 0) { this.x = width; } else if (this.x > width) { this.x = 0; } else if (this.y < 0) { this.y = height; } else if (this.y > height) { this.y = 0; } }; Ball.prototype.draw = function () { circle(this.x, this.y, 10, true); }; Ball.prototype.setDirection = function (direction) { if (direction === "up") { this.xSpeed = 0; this.ySpeed = -5; } else if (direction === "down") { this.xSpeed = 0; this.ySpeed = 5; } else if (direction === "left") { this.xSpeed = -5; this.ySpeed = 0; } else if (direction === "right") { this.xSpeed = 5; this.ySpeed = 0; } else if (direction === "stop") { this.xSpeed = 0; this.ySpeed = 0; } }; // Create the ball object var ball = new Ball(); // An object to convert keycodes into action names var keyActions = { 32: "stop", 37: "left", 38: "up", 39: "right", 40: "down" }; $("body").keydown(function (event) { var direction = keyActions[event.keyCode]; ball.setDirection(direction); }); setInterval(function () { ctx.clearRect(0, 0, width, height); ball.draw(); ball.move(); ctx.strokeRect(0, 0, width, height); }, 30); </script> </body>
相关推荐
柠檬班 2020-01-06
jacktangj 2019-12-01
javaer 2016-12-06
87457702 2018-09-30
lanseguhui 2019-06-30
梦想的翅膀 2016-12-06
81437106 2015-01-26
DreamLee 2013-10-11
AlisaClass 2013-07-30
luoshen 2013-04-16
yyzhu 2012-11-02
luochaotj 2012-07-20
vincent 2012-03-07
xunden 2017-01-12
AndrewFrank0zxy 2017-04-27
yxqfxd 2018-08-20
racy 2019-05-06
CommputerMac 2016-04-05