【发布时间】:2018-10-04 07:04:07
【问题描述】:
我正在开发一款 2D 平台游戏。背景中有star 对象,这些星星四处移动。我想在它们之间画出界线,而且我不费吹灰之力就做到了。我现在要做的是将alpha value(transparency) 添加到正在绘制的线条中。
我试图写一个方程,其中 alpha 值与两个对象之间的 distance 值成反比,但没有成功。
我如何在数学上表达以下规则?
距离越大,alpha值越小
例如,如果 距离 为 400,则透明度值应为 0(java.awt.Color 使用 0 作为 100% 透明度,使用 255 作为无透明度)
这是我想要实现的一个示例:
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var stars = [], // Array that contains the stars
FPS = 60, // Frames per second
x = 40, // Number of stars
mouse = {
x: 0,
y: 0
}; // mouse location
// Push stars to the array
for (var i = 0; i < x; i++) {
stars.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
radius: Math.random() * 1 + 1,
vx: Math.floor(Math.random() * 50) - 25,
vy: Math.floor(Math.random() * 50) - 25
});
}
// Draw the scene
function draw() {
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.globalCompositeOperation = "lighter";
for (var i = 0, x = stars.length; i < x; i++) {
var s = stars[i];
ctx.fillStyle = "#fff";
ctx.beginPath();
ctx.arc(s.x, s.y, s.radius, 0, 2 * Math.PI);
ctx.fill();
ctx.fillStyle = 'black';
ctx.stroke();
}
ctx.beginPath();
for (var i = 0, x = stars.length; i < x; i++) {
var starI = stars[i];
ctx.moveTo(starI.x,starI.y);
if(distance(mouse, starI) < 150) ctx.lineTo(mouse.x, mouse.y);
for (var j = 0, x = stars.length; j < x; j++) {
var starII = stars[j];
if(distance(starI, starII) < 150) {
//ctx.globalAlpha = (1 / 150 * distance(starI, starII).toFixed(1));
ctx.lineTo(starII.x,starII.y);
}
}
}
ctx.lineWidth = 0.05;
ctx.strokeStyle = 'white';
ctx.stroke();
}
function distance( point1, point2 ){
var xs = 0;
var ys = 0;
xs = point2.x - point1.x;
xs = xs * xs;
ys = point2.y - point1.y;
ys = ys * ys;
return Math.sqrt( xs + ys );
}
// Update star locations
function update() {
for (var i = 0, x = stars.length; i < x; i++) {
var s = stars[i];
s.x += s.vx / FPS;
s.y += s.vy / FPS;
if (s.x < 0 || s.x > canvas.width) s.vx = -s.vx;
if (s.y < 0 || s.y > canvas.height) s.vy = -s.vy;
}
}
canvas.addEventListener('mousemove', function(e){
mouse.x = e.clientX;
mouse.y = e.clientY;
});
// Update and draw
function tick() {
draw();
update();
requestAnimationFrame(tick);
}
tick();
canvas {
background: #232323;
}
<canvas id="canvas"></canvas>
【问题讨论】:
-
这是 JavaScript,不是 Java。确定最大距离是多少。将实际距离除以最大距离,乘以 255,然后从 255 中减去结果。
-
不是向我们展示一个有效的 javascript 示例,而是向我们展示您已经完成的工作。
-
@Jai 因为我的目标不是接收代码,而只是一个数学方程,我不相信插入一个用 js 制作的例子会受到伤害,因为它给出了预期的结果