Java - 使用两个对象之间的距离获取 0 - 255 之间的 alpha 值

Java - get alpha value between 0 - 255 using distance between two objects

我正在开发一款 2D 平台游戏。背景中有 star 个物体,这些星星四处移动。我想在它们之间划清界限,而且我已经毫不费力地做到了这一点。我现在要做的是向正在绘制的线条添加一个 alpha 值(透明度)。 我试图写一个等式,其中 alpha 值 与两个对象之间的 距离 的值成反比 但没有成功。

如何以数学方式表达以下规则?

The larger the distance is, the lesser value of alpha gets

例如,如果 距离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>

你应该使用:

((MAX_DISTANCE - distance) / MAX_DISTANCE) * 255

解释:
(MAX_DISTANCE - distance) 确保 较大 距离, 较小 结果。
然后,乘以 MAX_DISTANCE 并乘以 255,将其从 0-MAX_DISTANCE 缩放到 0-255。