我非常坚持这一点,到目前为止我所做的是创建了随机大小的矩形函数,它出现在画布的随机位置。我需要做的是每当我创建新的时使用JS绘制矩形,它就不会与现有的冲突。
<!DOCTYPE html>
<html>
<head>
<title>rectangles sucks</title>
</head>
<body>
<button id="buttonxD">press me!</button>
<script>
var body = document.getElementsByTagName("body")[0];
var canvas = document.createElement("canvas");
canvas.height = 500;
canvas.width = 500;
var context = canvas.getContext("2d");
body.appendChild(canvas);
function create() {
// Opacity
context.globalAlpha=0.7;
var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
context.fillStyle = color;
//Each rectangle's size is (20 ~ 100, 20 ~ 100)
context.fillRect(Math.random()*canvas.width, Math.random()*canvas.width, Math.random()*80+20, Math.random()*80+20);
}
document.getElementById('buttonxD').addEventListener('click', create);
</script>
</body>
</html>
我看到此功能用于检查碰撞检测
function isCollide(a, b) {
return !(
((a.y + a.height) < (b.y)) ||
(a.y > (b.y + b.height)) ||
((a.x + a.width) < b.x) ||
(a.x > (b.x + b.width))
);
}
但我未能将其整合到我的代码中...... 任何想法我应该用我现有的代码做什么不同,任何事都会有所帮助,谢谢!
答案 0 :(得分:2)
你需要一种方法来保持现有矩形的坐标。因此,如果您的新矩形不与其中一个发生碰撞,您可以检查该列表。
void init() {
glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
glClear (GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
// Lighting set up
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
// Set lighting intensity and color
GLfloat qaAmbientLight[] = {0.2, 0.2, 0.2, 1.0};
GLfloat qaDiffuseLight[] = {0.8, 0.8, 0.8, 1.0};
GLfloat qaSpecularLight[] = {1.0, 1.0, 1.0, 1.0};
glLightfv(GL_LIGHT0, GL_AMBIENT, qaAmbientLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, qaDiffuseLight);
glLightfv(GL_LIGHT0, GL_SPECULAR, qaSpecularLight);
// Set the light position
GLfloat qaLightPosition[] = {0, 0.758, 0.0, 1.0};
glLightfv(GL_LIGHT0, GL_POSITION, qaLightPosition);
}
void drawSun() {
glClear(GL_COLOR_BUFFER_BIT);
// Set material properties
GLfloat Yellow[] = {1.0, 0.647, 0.0, 1.0};
GLfloat White[] = {1.0, 1.0, 1.0, 1.0};
glMaterialfv(GL_FRONT, GL_AMBIENT, Yellow);
glMaterialfv(GL_FRONT, GL_DIFFUSE, Yellow);
glMaterialfv(GL_FRONT, GL_SPECULAR, White);
glMaterialf(GL_FRONT, GL_SHININESS, 60.0);
float x, y;
float radius = 0.095f;
float x_mid = 0;
float y_mid = 0.758;
glBegin(GL_POLYGON);
x = x_mid + (float)radius * cos(359 * PI / 180.0f);
y = y_mid + (float)radius * sin(359 * PI / 180.0f);
for (int j = 0; j < 360; j++)
{
glVertex2f(x, y);
x = x_mid + (float)radius * cos(j * PI / 180.0f);
y = y_mid + (float)radius * sin(j * PI / 180.0f);
glVertex2f(x, y);
}
glEnd();
}
如果它没有碰撞,这只会创建一个矩形。