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

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


我如何数学表达以下规则?


距离越大,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 );

}

茅侃侃
浏览 154回答 1
1回答

慕工程0101907

你应该使用:((MAX_DISTANCE&nbsp;-&nbsp;distance)&nbsp;/&nbsp;MAX_DISTANCE)&nbsp;*&nbsp;255说明:(MAX_DISTANCE - distance)可以确保较大的距离,更小的结果。然后,MAX_DISTANCE乘以 255,将其从 0-MAX_DISTANCE 缩放到 0-255。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java