我是JavaScript的新手,目前正在从事小型2D游戏,在html canvas元素中,我绘制了一个冰球和一个小的球门线,“游戏”的重点是将冰球投向目标。目前我的问题是我只是不知道如何使用鼠标控件移动冰球。我尝试使用this作为许多代码的参考,但似乎我正在努力将其他内容插入我自己的代码中。
这也是我的代码的一部分。 当前控制冰球的部分
document.addEventListener("mousedown", mouseDownHandler, false);
// When user clicks, the puck starts following the cursor
function mouseDownHandler(e) {
dx = 0;
dy = 0;
document.addEventListener("mousemove", mousemoveHandler, false);
document.addEventListener("mouseup", mouseUpHandler, false);
function mousemoveHandler(e) {
var relativeX = e.clientX - canvas.offsetLeft;
var relativeY = e.clientY - canvas.offsetTop;
if (relativeX > 0 && relativeX < canvas.width) {
x = relativeX - 18 / 2;
} if (relativeY > 0 && relativeY < canvas.height) {
y = relativeY - 20 / 2;
}
}
function mouseUpHandler(e) {
dx = -dx + 1;
dy = -dy - 1;
x += 0;
y += 0;
document.removeEventListener("mousemove", mousemoveHandler, false);
}
}
然后是我的变量:
// Variables used
var canvas = document.getElementById("gameArea");
var ctx = canvas.getContext("2d");
// Coordinates used for the puck
var x = canvas.width/2;
var y = canvas.height/2;
// Coordinates used to make the puck "move" as a placeholder"
var dx = 0;
var dy = 0;
// Gives the puck a radius that is used for calculations
var puckRadius = 10;
var goalieRadius = 57;
// Variables for goalie
var z = canvas.width/2;
var a = 5;
//variable for counting score
var score = 0;
// Variables for goal size and location
var goalHeight = 10;
var goalWidth = 115;
var goalX = (canvas.width-goalWidth)/2;
如果您需要其他任何帮助,请告诉我!
编辑:https://jsfiddle.net/6gn48dbq/1/也是作品的精髓!
答案 0 :(得分:1)
所以请关注我的评论...
您需要在鼠标中添加速度:
function mouseUpHandler(e) {
dx = -dx + speed;
dy = -dy - speed;
...然后,该速度可以通过滑块<input type="range">
来控制
在抽奖的每一次通过中都施加摩擦:
function draw() {
dx *= friction;
dy *= friction;
这是一个有效的示例:
https://jsfiddle.net/nfdyLv61/