我正在开发2D平台游戏。背景中有star
个对象,这些星星在四处移动。我想在它们之间画线,并且我已经做了很多努力。我现在想做的是在绘制的线条上添加一个alpha
值(透明度)。
我试图写一个方程,其中alpha值与两个对象之间的距离值成反比,但没有成功。
如何数学表达以下规则?
距离越大,alpha值越小
例如,如果 distance 为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>
答案 0 :(得分:2)
您应该使用:
((MAX_DISTANCE - distance) / MAX_DISTANCE) * 255
说明:
(MAX_DISTANCE - distance)
确保距离较大,结果较小。
然后,乘以MAX_DISTANCE
乘以255,将其从0-MAX_DISTANCE缩放为0-255。