首页 > 解决方案 > p5js 图像不会旋转

问题描述

我正在尝试用 p5js 编写游戏并使用角色图像(当某个变量为真时)。然而,该图像拒绝旋转,正方形旋转(当变量设置为 false 时)但图像拒绝旋转。完整的代码在这里,播放器的绘图代码是这样的:

show(){
    push()
    if (!this.squid){
        rotate(this.dir)
        fill(this.color[0],this.color[1],this.color[2])
        square(this.pos.x,this.pos.y,16)
    }else{
        rotate(this.direction-90)
        tint(this.color[0],this.color[1],this.color[2])
        image(squid,this.pos.x,this.pos.y)
    }
    pop()
}

标签: javascriptp5.js

解决方案


我认为您只是在应该引用this.direction的函数中引用了错字。show()this.dir

class Player {
  constructor(x, y, r, g, b) {
    this.pos = createVector(x, y)
    this.color = [r, g, b]
    this.squid = true
    this.dir = 45
  }
  show() {
    push()
    if (!this.squid) {
      translate(this.pos.x, this.pos.y)
      rotate(this.dir)
      fill(this.color[0], this.color[1], this.color[2])
      square(0, 0, 16)
    } else {
      tint(this.color[0], this.color[1], this.color[2])
      translate(this.pos.x, this.pos.y)
      // You had this.direction which was undefined
      rotate(this.dir - 90)
      image(squid, 0, 0)
    }
    pop()
  }
}

let testplayer
let squid

function preload() {
  squid = loadImage("https://f1201776-831f-4d61-a007-a09053ab2a30.id.repl.co/squid.png")
}

function setup() {
  resizeCanvas(window.innerWidth, window.innerHeight)
  angleMode(DEGREES)
  testplayer = new Player(20, 20, 0xff, 0x0, 0x0)
  rectMode(CENTER)
  imageMode(CENTER)
}

function draw() {
  background(0x22)
  // Adding animated rotation for demonstration purposes.
  testplayer.dir += 1;
  testplayer.show()
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>


推荐阅读