首页 > 解决方案 > 在 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>

标签: javascriptprocessingp5.js

解决方案


使用push()pop()存储和恢复当前样式设置和转换。这也保存和恢复了当前矩阵。

push()在汽车绘制之前 ( car.show()) 和pop()之后。这导致转换car.show()仅应用于汽车:

function draw() {
    background(100);

    push();
    car.show();
    pop();

    car.move();

    // [...]
}

推荐阅读