实现方法思路:用bitmapData.getPixel32方法获取像素点值,0为透明区,判断是否为路面
package
{
import flash.display.*;
import flash.events.KeyboardEvent;
import flash.events.Event;
import flash.geom.Point;
import flash.utils.getTimer;
import flash.ui.Keyboard;
import flash.filters.GlowFilter;
public class Main extends Sprite
{
/**
* 人物
*/
private var _person:MovieClip;
/**
* 是否移动
*/
private var _moving:Boolean;
/**
* 地图
*/
private var _map:Bitmap;
/**
* 移动速度
*/
private var _speed:int = 2;
public function Main()
{
//创建地图
this._map = new Bitmap(new ResBitmapData);
this.addChild(this._map);
//创建人物
this._person = new ResPerson();
this._person.gotoAndStop(1);
this.addChild(this._person);
//初始位置:执行两次才可以定位正确角度
this.moving();
this.moving();
//加入监听器
stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown );
stage.addEventListener(KeyboardEvent.KEY_UP, keyup);
addEventListener(Event.ENTER_FRAME, movePerson);
}
private function keydown($evt:KeyboardEvent):void
{
if ($evt.keyCode == Keyboard.RIGHT)
{
this._person.gotoAndStop(2);
this._moving = true;
}
}
private function keyup($evt:KeyboardEvent):void
{
if ($evt.keyCode == Keyboard.RIGHT)
{
this._person.gotoAndStop(1);
this._moving = false;
}
}
private function movePerson($evt:Event = null)
{
if (this._moving)
{
this.moving();
}
}
private function moving():void
{
//移动到下个点
var step1:Point = new Point(this._person.x, this._person.y);
var step2:Point = new Point(this._person.x + this._speed, 0);
var y:uint
for (y = 0; y < this._map.height; y++)
{
if (this._map.bitmapData.getPixel32(step2.x, y) != 0 && this._map.bitmapData.getPixel32(step2.x, y - 1) == 0)
{
step2.y = y;
break;
}
}
this._person.x = step2.x;
this._person.y = step2.y;
//计算角度:因为路线坡度的原因,角度的点和实际移动的点要定位的更远些
//如果速度为1,当前点移到下一个点是向下的角度,但是有可能第三个点开始为向上的角度
//这时人物角度就有问题,可以改变下句代码中的:5,这个值看效果
step2 = new Point(this._person.x + this._speed * 5, 0);
for (y = 0; y < this._map.height; y++)
{
if (this._map.bitmapData.getPixel32(step2.x, y) != 0 && this._map.bitmapData.getPixel32(step2.x, y - 1) == 0)
{
step2.y = y;
break;
}
}
var angle = Math.atan2(step2.y - step1.y, step2.x - step1.x) / Math.PI * 180;
this._person.rotation = angle;
}
}
}
源文件360云盘地址:
http://yunpan.cn/QiJhxS2caqPpQ
访问密码 4e1d