【发布时间】:2014-07-16 17:33:00
【问题描述】:
我的对象是通过鼠标移动控制的(目前)...由于它的控制方式(对象总是远离光标),我想添加约束,以便它不仅留在舞台内,而且在它们之间留出空间运动边界和舞台边缘......
因此,如果对象移动得太靠近舞台限制,则光标将有空间将其移回游戏区域。
目前,我在舞台内动态创建了一个矩形,我想我可以将运动限制在这个矩形的区域内,这样可以在边缘周围留出足够的空间......我该怎么做?
但是,如果有更好/更简单的方法来获得所需的结果......我会全力以赴。
import flash.events.KeyboardEvent;
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Shape;
var rectangle:Shape = new Shape;
//initialize "rectangle" shape
rectangle.graphics.beginFill(0xCCCCCC);
//choose colour for fill - black
rectangle.graphics.drawRect(50, 50, 450, 300);
//draw shape
rectangle.graphics.endFill();
//end fill
addChild(rectangle);
//add "rectangle" to stage
var hero:MovieClip = new hero_mc();
//initialize "hero" object - "hero_mc"
hero.x = stage.stageWidth / 2;
hero.y = stage.stageHeight / 2;
//set spawn location, centre stage
addChild(hero);
//add "hero" to stage
function cursorHold(evt:Event):void {
trace("moving");
var dX:Number = hero.x - stage.mouseX;
//get adjacent
var dY:Number = hero.y - stage.mouseY;
//get opposite
var r:Number = Math.sqrt(Math.pow(dX, 2) + Math.pow(dY, 2));
//get hypotenuse
var angle:Number = Math.acos(dX/r)*180/Math.PI;
//get angle
var radians:Number = deg2rad(angle);
//call conversion function for angle
var speed:Number = 1.5;
//set speed
var xV:Number = Math.cos(radians) * speed;
//get x velocity
var yV:Number = Math.sin(radians) * speed;
//get y velocity
hero.x += xV;
//move hero along new x velocity
if (stage.mouseY > hero.y) {
hero.y -= yV;
} else {
hero.y += yV;
}
//move hero along new y velocity
}
function deg2rad(deg:Number):Number {
return deg * (Math.PI / 180);
//convert degrees to radians
}
stage.addEventListener(Event.ENTER_FRAME, cursorHold, false, 0, true);
这是一张图片:https://lh5.googleusercontent.com/lWG8uR9MLK32oHXX26JBiLtBdvmiICFuxOQakQESnBY=w552-h402-no
因此,“hero_mc”不应该能够移动到白色区域,但它仍然应该移动(用鼠标移动刮擦边缘。
如果代码一团糟,我深表歉意...我对 ActionScript 3.0 还是很陌生。任何关于清理它的提示也非常受欢迎。
【问题讨论】:
标签: actionscript-3 flash game-physics collision stage