AS3 - 相对于角度移动阵列对象
Posted
技术标签:
【中文标题】AS3 - 相对于角度移动阵列对象【英文标题】:AS3 - Move Array objects relative to angle 【发布时间】:2018-05-14 17:30:37 【问题描述】:我正在创建一个游戏,我需要将船只以设定的速度朝向它们所面对的角度移动。我已经使用此代码在游戏中的其他地方移动了奇异的船只,但我认为将它们放在一个数组中会很复杂。
任何帮助将不胜感激。
var ship1 = this.addChild(new Ship());
var ship2 = this.addChild(new Ship());
var ship3 = this.addChild(new Ship());
var ship4 = this.addChild(new Ship());
var shipSpeed1 = 10;
var shipArray: Array = [];
shipArray.push(ship1, ship2, ship3, ship4);
for (var i: int = 0; i < shipArray.length; i++)
var randomX: Number = Math.random() * stage.stageHeight;
var randomY: Number = Math.random() * stage.stageHeight;
shipArray[i].x = randomX;
shipArray[i].y = randomY;
shipArray[i].rotation = 90;
shipArray[i].x += Math.sin(shipArray[i].rotation * (Math.PI / 180)) * shipSpeed1;
shipArray[i].y -= Math.cos(shipArray[i].rotation * (Math.PI / 180)) * shipSpeed1;
我也将它包含在同一个函数中,但我也无法让它工作。我又一次有了这个工作
if (shipArray[i].x < 0) //This allows the boat to leave the scene and
enter on the other side.
shipArray[i].x = 750;
if (shipArray[i].x > 750)
shipArray[i].x = 0;
if (shipArray[i].y < 0)
shipArray[i].y = 600;
if (shipArray[i].y > 600)
shipArray[i].y = 0;
【问题讨论】:
显示你用来移动奇异飞船的代码。现在,您的代码不会在初始位置之外移动任何内容。 @BadFeelingAboutThis var ship = evt.currentTarget; ship.x += Math.sin(ship.rotation * (Math.PI / 180)) * randomSpeed(4, 15); //使用我的随机数控制船 ship.y -= Math.cos(ship.rotation * (Math.PI / 180)) * randomSpeed(4, 15);完全一样。 【参考方案1】:首先,您需要将代码分成生成/初始化阶段和更新阶段。
类似于以下内容:
var shipArray: Array = [];
//spawn and set initial values (first phase)
//spawn 4 new ships
var i:int;
for(i=0;i<4;i++)
//instantiate the new ship
var ship:Ship = new Ship();
//add it to the array
shipArray.push(ship);
//set it's initial x/y value
ship.x = Math.random() * (stage.stageWidth - ship.width);
ship.y = Math.random() * (stage.stageHeight - ship.height);
//set it's initial rotation
ship.rotation = Math.round(Math.random() * 360);
//set the ships speed (dynamic property)
ship.speed = 10;
//add the new ship to the display
addChild(ship);
//NEXT, add an enter frame listener that runs an update function every frame tick of the application
this.addEventListener(Event.ENTER_FRAME, gameUpdate);
function gameUpdate(e:Event):void
//loop through each ship in the array
for (var i: int = 0; i < shipArray.length; i++)
//move it the direction it's rotated, the amount of it's speed property
shipArray[i].x += Math.sin(shipArray[i].rotation * (Math.PI / 180)) * shipArray[i].speed;
shipArray[i].y -= Math.cos(shipArray[i].rotation * (Math.PI / 180)) * shipArray[i].speed;
【讨论】:
新问题到底是什么?船只离开屏幕?以上是关于AS3 - 相对于角度移动阵列对象的主要内容,如果未能解决你的问题,请参考以下文章
ActionScript 3 AS3中心一个DisplayObject相对于另一个