完全控制很多对象的Javascript [英] Full control of many objects Javascript
问题描述
我正在开发一款javascript游戏,它会产生并终止形状。因此,我需要完全控制这些正在产生的形状。我想做以下事情,但我不知道如何做到这一点:
- 我想定义一个构造函数
Shape
。 - 然后,我想创建一个函数,当它被调用时,它适用于所有
Shape
存在并且能够更改每个属性。 (例如,我调用函数moveAll()
,并将所有形状的this.y
增加1。) - 我也希望能够用一个函数终止一个特定的
Shape
,或者添加一个Shape
带一个函数。
我的主要问题是:
var x = new Shape();
var y = new Shape();
...
我不想制作一百万个变量。我需要一种能够立即制作大量形状的方法,并且仍然可以单独控制每一种形状。如果我创建了一个数组,我将如何单独控制每件事?
任何事情都有帮助,我只需要理解构造函数概念的基础。
解决方案您可以制作一组形状:
let shapes = []
//这将创建6个形状
for(let i of [0,1,2,3,4 ,5]){
shapes.push(new Shape())
}
<如果一个形状有一个
id
,您可以终止它。 //增加id计数器
让id = 0
// x和y是可选的起始位置
函数Shape(x,y){
this.id = id ++
this.y = y || 0
this.x = x || 0
}
//从数组中删除形状
函数terminate(id){$ b $ shapes = shapes.filter(shape => shape.id! == b)
}
//或者添加一个形状
函数spawn(){
shapes.push(new Shape())
}
现在您已经拥有了自己的形状。
移动所有形状的最简单的方法是这样的:
function moveAll(){
shapes.forEach shape => shape.y ++)
}
运行时间会随着数字
$ b更新
moveAll
,每个请求
function moveAll(){
shapes.forEach(shape => {
if(shape.type === true){
shape。 y ++
} else {
shape.y--
}
})
}
I am working on a game in javascript that spawns and terminates shapes. Therefore, I need full control over these shapes that are being spawned. I want to do the following, but I am not sure on how to do it:
- I want to define a constructor
Shape
. - Then, I want to make a function so that when it is called, it applies to ALL of the
Shape
in existence and being able to change each ones attribute. (For example, I call functionmoveAll()
and all of the shapes'this.y
increments by one.) - I also want to be able to terminate a specific
Shape
with a function, or add aShape
with a function.
My main problem is this:
var x = new Shape(); var y = new Shape(); ...
I don't want to make a million variables. I need a way to make tons of shapes at once and still be able to control each one individually. And if I made an array, how would I control everything individually?
Anything helps, I just need a basis to understand the concept of constructors. Thanks in advance!
解决方案You could make an array of shapes:
let shapes = [] // this will create 6 shapes for(let i of [0,1,2,3,4,5]) { shapes.push(new Shape()) }
If a shape has an
id
you can terminate it:// incrementing id counter let id = 0 // x and y are optional starting positions function Shape(x, y) { this.id = id++ this.y = y || 0 this.x = x || 0 } // remove the shape from the array function terminate(id) { shapes = shapes.filter(shape => shape.id !== id) } // or add a shape function spawn() { shapes.push(new Shape()) }
Now you have your shapes.
The simplest way to move all shapes would be something like this:
function moveAll() { shapes.forEach(shape => shape.y++) }
Runtime for this will increase as the number of shapes increase.
updated
moveAll
, per requestfunction moveAll() { shapes.forEach(shape => { if(shape.type === true) { shape.y++ } else { shape.y-- } }) }
这篇关于完全控制很多对象的Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- I want to define a constructor