我一直在尝试使用p5.js,并且在旋转方面遇到了一些麻烦。根据文档,我应该能够使用rectMode(CENTER);
围绕矩形的中心旋转矩形,尽管这似乎不起作用。我尝试将语句移动到代码的各个部分,但是当您按左右箭头键时,它似乎仍在(0,0)周围旋转。任何帮助表示赞赏!
var MAX_VELOCITY = 1;
class Car{
constructor(x,y){
this.x = x;
this.y =y;
this.velocity = 0;
this.accel = 0;
this.width = 40;
this.height =80;
this.angle = 0;
}
show(){
fill(225,0,255);
stroke(0);
rotate(this.angle);
rect(this.x, this.y, 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;
}
}
function setup(){
window.canvas = createCanvas(600,600);
rectMode(CENTER);
car = new Car(width/2, height/2);
var flagger = false;
}
function draw(){
background(100);
car.show();
car.move();
if(car.y < 0 ){
car.y = 0;
}
if(car.y + car.height > 600){
car.y=600 - car.height
}
}
function keyPressed(){
if (keyCode === UP_ARROW){
car.accel = -.1;
flagger = false
console.log("Moving Up");
}
if (keyCode === DOWN_ARROW){
car.accel = .1;
flagger = false;
console.log("Moving Down");
}
if (keyCode === RIGHT_ARROW){
car.angle += .1;
}
if (keyCode === LEFT_ARROW){
car.angle += -.1;
}
}
<script src="https://cdn.jsdelivr.net/npm/p5@0.10.2/lib/p5.js"></script>
答案 0 :(得分:0)
的确,使用 rectMode(CENTER),您可以控制p5.js如何解释对rect()的调用的x和y坐标。但这并不意味着矩形将围绕其中心旋转。所有转换都是相对于来源的,它位于屏幕的左上方。
因此,要围绕矩形的中心旋转矩形,需要将原点移动到要绘制矩形的位置。这是通过调用 translate()完成的。然后旋转并在x = 0和y = 0处绘制矩形,这是现在的新原点。
var MAX_VELOCITY = 1;
class Car {
constructor(x, y) {
this.x = x;
this.y = y;
this.velocity = 0;
this.accel = 0;
this.width = 40;
this.height = 80;
this.angle = 0;
}
show() {
fill(225, 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;
}
}
function setup() {
window.canvas = createCanvas(600, 600);
rectMode(CENTER);
car = new Car(width / 2, height / 2);
var flagger = false;
}
function draw() {
background(100);
car.show();
car.move();
if (car.y < 0) {
car.y = 0;
}
if (car.y + car.height > 600) {
car.y = 600 - car.height
}
}
function keyPressed() {
if (keyCode === UP_ARROW) {
car.accel = -.1;
flagger = false
console.log("Moving Up");
}
if (keyCode === DOWN_ARROW) {
car.accel = .1;
flagger = false;
console.log("Moving Down");
}
if (keyCode === RIGHT_ARROW) {
car.angle += .1;
}
if (keyCode === LEFT_ARROW) {
car.angle += -.1;
}
}
<script src="https://cdn.jsdelivr.net/npm/p5@0.10.2/lib/p5.js"></script>