as3 hitTestObject 与 for 循环
我正在构建一个吃豆人风格的游戏,我希望缩短我的代码。 该阶段包含 92 个实例,实例名称为 food1、food2 等。 当玩家(吃豆人)点击其中一个实例时,我想调用一个函数。
我开始这样写……它有效,但我不想重复这个 92 次!
if( player.hitTestObject(food1) ) {
updateScore();
}
if( player.hitTestObject(food2) ) {
updateScore();
}
现在我正在尝试一些类似的事情,但还没有成功。
function collectFood() {
var i:Number;
var pGroup:String
for (i=0; i<92; i++) {
pGroup= "food" + i;
if( player.hitTestObject( MovieClip(pGroup) ) ) {
pCount+= 1;
MovieClip(pGroup).y=-300;
updateScore();
}
}
}
感谢您的帮助!
I am building a pacman style game, and I am looking to shorten my code.
The stage contains 92 instances with instance names of food1, food2, etc.
When the player(pacman) hits one of the instances Im wanting to call a funcion.
I started writing it out like this... it works but I don't want to duplicate this 92 times!
if( player.hitTestObject(food1) ) {
updateScore();
}
if( player.hitTestObject(food2) ) {
updateScore();
}
Now I'm trying something along these lines, but with no success yet.
function collectFood() {
var i:Number;
var pGroup:String
for (i=0; i<92; i++) {
pGroup= "food" + i;
if( player.hitTestObject( MovieClip(pGroup) ) ) {
pCount+= 1;
MovieClip(pGroup).y=-300;
updateScore();
}
}
}
Thanks for any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
考虑将食物存储在
数组
中。设置一个数组:
将您的食物添加到此数组中(如果适用):
然后您可以使用
foreach
来遍历此数组中的项目:如果您的食物已放在舞台上并且想要要将它们全部添加到此数组中,只需执行以下操作:
我强烈建议您查看 面向对象编程(OOP) 用于 ActionScript-3。使用 OOP,您将能够为您的
Food
和 封装一块食物应该做的一切。它还将允许您拥有更加清晰易读的代码,特别是在上面的
for every
循环中,它可能如下所示:作为美观的好处,使用像 FlashDevelop 将根据您添加到 Food 类的内容提供非常有用的工具提示,例如:
Look into storing your food in an
Array
.Set up an Array:
Add your food items into this array (wherever applicable):
And then you can use
for each
to run through the items in this Array:If you have your food on the stage and want to add them all into this Array, just do this:
I strongly suggest that you look into Object-oriented programming (OOP) for ActionScript-3. Using OOP you'll be able to create a
class
for yourFood
and encapsulate everything that a piece of Food should do.It will also allow you to have much cleaner and readable code, particularly in the above
for each
loop, which could look like this:As an aesthetic benefit, using an application like FlashDevelop will provide extremely helpful tooltips based on what you add to your Food class, eg: