javascript 如何在不进入对象内部的情况下更新对象的值?

h6my8fg2  于 2023-01-24  发布在  Java
关注(0)|答案(1)|浏览(112)

我目前正在尝试编程塔防游戏的帮助下,一些youtube教程和以前的经验.现在我试图通过点击按钮更新塔半径的值,但它似乎不工作:

let towerRadius = 250
class Building extends Sprite {
    constructor({position = {x: 0, y: 0}}) {
        super({position, imageSrc: 'img/tower.png', frames: {max: 19}, offset: {x: 0, y: -80}})
        this.width = 64 * 2
        this.height = 64
        this.center = {
            x: this.position.x + this.width / 2,
            y: this.position.y + this.height / 2,
        }
        this.projectiles = []
        this.radius = towerRadius
        this.target
    }
    draw() {
       super.draw()
      c.beginPath()
        c.arc(this.center.x, this.center.y, this.radius, 0, Math.PI * 2)
        c.fillStyle = 'rgba(0, 0, 255, 0.15'
        c.fill()
    } 
    update() {
        this.draw()
        if (this.target || (!this.target && this.frames.current !== 0)) super.update()

        if (this.target && this.frames.current === 6 && this.frames.elapsed % this.frames.hold === 0) this.shoot()
        
    }
    shoot() {
        this.projectiles.push(
            new Projectile({
                position: {
                    x: this.center.x - 20,
                    y: this.center.y - 110
                },
                enemy: this.target
            })
        )
    }
}
let currentRangeUpgrade = 1
var upgradeTowerButton = document.getElementById("upgradeRangeButton")
upgradeTowerButton.addEventListener('click', (event) => {
    if(coins - currentRangeUpgrade * 100 >= 0) {
    coins -= currentRangeUpgrade * 100
    document.querySelector('#coins').innerHTML = coins
    towerRadius += 1000
    document.querySelector('#upgradeRangeText').style.display = 'flex'
    setTimeout(function() {
    document.querySelector('#upgradeRangeText').style.display = 'none'
    }, 3000);
    currentRangeUpgrade++
    document.querySelector('#upgradeRangeButton').innerHTML = "UPGRADE RANGE: " + currentUpgrade * 100
    }
})

我尝试通过将对象的初始半径设置为towerRadius来更改towerRadius,但似乎没有任何变化,即使控制台记录了我试图获得的半径。

sqxo8psd

sqxo8psd1#

代码中的问题是towerRadius是一个原语,所以它是通过值传递的。一旦它将this.radius设置为towerRadius,它就不会改变,无论towerRadius发生什么。为了在不改变整个代码库中的代码的情况下使它正确,可以使用getter:

constructor({position = {x: 0, y: 0}}) {
        super({position, imageSrc: 'img/tower.png', frames: {max: 19}, offset: {x: 0, y: -80}})
        this.width = 64 * 2
        this.height = 64
        this.center = {
            x: this.position.x + this.width / 2,
            y: this.position.y + this.height / 2,
        }
        this.projectiles = []
        // remove this line of code
        // this.radius = towerRadius
        this.target
    }

    // add this to your class so whenever it looks for radius, it recomputes it (here just by returning the global variable)
    get radius () {
        return towerRadius
    }

希望对你有帮助!

相关问题