gpt4 book ai didi

javascript - 使用 Canvas 创建可指向的第一人称射击枪

转载 作者:行者123 更新时间:2023-11-30 15:35:48 24 4
gpt4 key购买 nike

我一直在尝试寻找一种方法来渲染如何用 Canvas 制作枪支的结果,该枪支可以指向光标所在的位置。我对我应该做什么有一个基本的想法:

<!doctype html>
<html>
<head>
<title>Block Shooter</title>
</head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<body>
<center>
<div id="introContainer"><h1 id="intro">Welcome to Block Shooter</h1></div>
<button id="skip" style="position: absolute; bottom: 50px; left:610px">Skip Intro</button>
<canvas id="canvas" width="1200" height="600" style="border: 1px solid black;"></canvas>
<script>

// Variables

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var gunWidth = 80;
var gunLength = 150;

$("#canvas").mousemove(function (event) {
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.beginPath();
ctx.lineWidth = gunWidth;
ctx.strokeStyle = "black";
ctx.moveTo(canvas.width / 2 - gunWidth / 2, canvas.height + 100);
ctx.lineTo(event.offsetX, event.offsetY);
ctx.stroke();
ctx.closePath();

ctx.beginPath();
ctx.lineWidth = gunWidth;
ctx.strokeStyle = "white";
ctx.moveTo(event.offsetX, event.offsetY);
ctx.lineTo(canvas.width / 2 - gunWidth / 2, canvas.height - gunLength);
ctx.stroke();
ctx.closePath();

})

</script>
</center>
</body>

</html>

我不知道下一步该做什么。有更好的方法吗?如果是,请提供示例。谢谢!

最佳答案

不幸的是,交互式图形编程很快就进入了数学……用以下内容替换 $(#canvas).mousemove( 函数中的内容

           ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.beginPath();
ctx.lineWidth = gunWidth;
ctx.strokeStyle = "black";
//get dimensions of canvas
//for performance this should be moved out of the
//mousemove and up to where your other global variables canvas and ctx are.
var dimensions=event.target.getBoundingClientRect();
var middle=dimensions.left+(dimensions.width/2)
ctx.moveTo(middle,0);
//get mousex relative to canvas
var mousex=event.clientX-dimensions.left;
//get mousey relative to canvas
var mousey=event.clientY-dimensions.top;
var ydistance=mousey;
var xdistance=mousex-middle
//distance formula
var distance=Math.sqrt((xdistance*xdistance)+(ydistance*ydistance))
//http://math.stackexchange.com/questions/175896/finding-a-point-along-a-line-a-certain-distance-away-from-another-point
var gunlength=200;
var drawx=(gunlength*(xdistance/distance))+middle
var drawy=gunlength*(ydistance/distance)

ctx.lineTo(drawx, drawy);


ctx.stroke();
ctx.closePath();

这将使枪保持相同的大小......你需要改变一些东西让枪回到 Canvas 的底部(HTML Canvas 有一个倒置的 y 轴,我没有在演示中考虑到这一点)

关于javascript - 使用 Canvas 创建可指向的第一人称射击枪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41560395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com