javascript - 在 p5.js 中绘图时转换坐标
问题描述
我正试图弄清楚如何为我正在开发的这款汽车游戏制作赛道。当前的问题是,当我绘制轨道时,绘图的坐标相对于汽车的坐标进行了变换。抱歉,这有点难以解释,但是如果您查看下面的代码,您就会明白我的意思。然后是让所有图纸都保留在最新框架上的问题,但这是另一天的问题。(请忽略汽车留下的痕迹,一旦我弄清楚如何确保在最新框架上重新绘制图纸,这将得到修复。我真的对这个 JS 有点困惑,所以任何和所有的帮助都非常感谢!
var MAX_VELOCITY = 3;
class Car {
constructor(x, y, angle) {
this.x = x;
this.y = y;
this.angle = angle;
this.velocity = 0;
this.accel = 0;
this.width = 40;
this.height = 80;
}
show() {
fill(255, 0, 255);
stroke(0);
translate(this.x, this.y);
rotate(this.angle);
rect(0, 0, this.width, this.height);
}
move() {
this.velocity += this.accel;
if (this.velocity > MAX_VELOCITY) {
this.velocity = MAX_VELOCITY;
}
if (this.velocity < -MAX_VELOCITY) {
this.velocity = -MAX_VELOCITY;
}
this.y += this.velocity * Math.sin(this.angle + Math.PI / 2);
this.x += this.velocity * Math.cos(this.angle + Math.PI / 2);
}
}
function setup() {
WINDOW_HEIGHT = 600;
WINDOW_WIDTH = 600;
window.canvas = createCanvas(WINDOW_HEIGHT, WINDOW_WIDTH);
rectMode(CENTER);
car = new Car(width / 2, 500, -Math.PI / 2 + Math.PI / 2);
console.log("Car Created");
var flagger = false;
}
function draw() {
// background(100);
car.show();
car.move();
// console.log("X: ", car.x);
// console.log("Y: ", car.y)
console.log("X: ", mouseX)
console.log("Y: ", mouseY)
if (car.y < car.height / 2) {
car.y = car.height / 2;
}
if (car.x < car.height / 2) {
car.x = car.height / 2;
}
if (car.y > height - car.height / 2) {
car.y = height - car.height / 2;
}
if (car.x > width - car.height / 2) {
car.x = width - car.height / 2;
}
controls();
if (mouseIsPressed === true) {
line(
mouseX - car.x,
mouseY - car.y,
pmouseX - car.x,
pmouseY - car.y
);
}
// console.log("Velocity: ", car.velocity);
// console.log("Acceleration: ", car.accel);
}
function controls() {
if (keyIsDown(UP_ARROW)) {
car.velocity += -1;
flagger = false;
}
if (keyIsDown(DOWN_ARROW)) {
car.velocity += 1;
flagger = false;
}
if (keyIsDown(RIGHT_ARROW)) {
car.angle += 0.1;
}
if (keyIsDown(LEFT_ARROW)) {
car.angle -= 0.1;
}
}
<script src="https://cdn.jsdelivr.net/npm/p5@0.10.2/lib/p5.js"></script>
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Car Game</title>
<style>
body {
padding: 0;
margin: 0;
}
</style>
</head>
<body>
</body>
</html>
解决方案
推荐阅读
- android - 使用 vscode 调试器调试 React Native
- reactjs - 异步等待 redux this.props.func 调用?
- python - 初始化要在 SelectField 中使用的 Flask WTFForm 类变量
- hadoop - 目录文件未使用命令“hadoop fs -put”复制到 HDFS
- ubuntu - 在 Ubuntu 18.04 中启动 Xampp 时遇到 MySQL 错误
- c# - Linq查询不使用表的对象获取表的记录
- android - Unity游戏中出现广告时如何重启手机?
- flutter - Flutter v1.0下的类TickerProviderStateMixin undefined
- java - 如何在 selenium 中使用 java 从 excel 工作表中检索 0.00000000 等十进制值?
- excel - VBA - 选择指定范围时在下一个单元格上调用函数