所以我是Java语言的新手,并试图使它像一个游戏...在这个游戏中,红球可以移动,蓝球应该跟随红球,就像蓝球应该朝向红球一样
我有红球x,y的坐标 和蓝色球x2,y2的坐标
如何使蓝球吸引红球???
这是我的代码
const canvas = document.getElementById("game");
const context = canvas.getContext("2d");
canvas.width = window.innerWidth-20;
canvas.height = window.innerHeight-20;
let gameover = false;
let x = canvas.width / 2;
let y = canvas.height / 2;
let dx = 0;
let dy = 0;
x3=y3=0;
virx = new Array();
viry = new Array();
for (i=0; i<25; i++)
{
virx.push(Math.floor((Math.random() * window.innerWidth-20) + 1));
viry.push(Math.floor((Math.random() * window.innerHeight-20) + 1));
}
const state = {
"ArrowRight": false,
"ArrowLeft": false,
"ArrowUp": false,
"ArrowDown": false
}
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.arc(x, y, 10, 0, Math.PI * 2, false);
context.fillStyle = "red";
context.fill();
context.closePath();
for (i=0; i<25; i++)
{
if (virx[i]<x) {
x3=virx[i]+1;
y3=point(x,y,x3,viry[i]);
}
else {
x3=virx[i]-1;
y3=point(x,y,x3,viry[i]); // <---- and something is supposed to happen here
}
context.beginPath();
context.arc(virx[i], viry[i], 10, 0, Math.PI * 2, false);
context.fillStyle = "blue";
context.fill();
context.closePath();
}
}
function logic() {
const direction = determineDirection();
if (direction.dx) {
dx = dx + direction.dx;
}
if (direction.dy) {
dy = dy + direction.dy;
}
x = x + dx;
y = y + dy;
if (dx > 0) {
dx -= 0.02;
}
if (dx < 0) {
dx += 0.02;
}
if (dy > 0) {
dy -= 0.02;
}
if (dy < 0) {
dy += 0.02;
}
}
function play() {
draw();
logic();
}
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function point(x1,y1,x2,y2)
{
m=(y2-y1)/(x2-x1);
b=y2-(m*x2); // according to what i know this function gonna play
y=(m*x1)+b; // major role in this thing
return(y);
}
function determineDirection() {
const {
ArrowRight,
ArrowLeft,
ArrowUp,
ArrowDown
} = state
if (ArrowRight && ArrowUp) {
return {
dx: .040,
dy: -.040
};
}
if (ArrowRight && ArrowDown) {
return {
dx: .040,
dy: .040
};
}
if (ArrowLeft && ArrowUp) {
return {
dx: -.040,
dy: -.040
};
}
if (ArrowLeft && ArrowDown) {
return {
dx: -.040,
dy: .040
};
}
if (ArrowLeft) {
return {
dx: -.040,
dy: 0
}
}
if (ArrowRight) {
return {
dx: .040,
dy: 0
}
}
if (ArrowUp) {
return {
dx: 0,
dy: -.040
}
}
if (ArrowDown) {
return {
dx: 0,
dy: .040
}
}
return {
dx: 0,
dy: 0
}
}
function keyDownHandler({
key
}) {
state[key] = true;
}
function keyUpHandler({
key
}) {
state[key] = false;
}
setInterval(play, 10);