我以为这是一个简单的任务,但我错了。
我使用精灵来显示图像,当用户拖动它(MOUSE_DOWN 和 MOUSE_MOVE)时,我得到了位置MOUSE_MOVE
并计算了偏移量:
var current: Point = new Point(event.localX, event.localY);
sprite.x = current.x - start.x;
sprite.y = current.y - start.y;
它有效但不流畅。有更好的解决方案吗?
更新
经过一天的调试,终于找到了原因。
更大的fps可以让它更流畅,但这不是这个问题的关键。
关键是我应该stage
用来听MOUSE_MOVE
,而不是图像本身。在获取鼠标位置时,我应该使用event.stageX/Y
(or stage.mouseX/Y
),而不是event.localX/Y
. 从event.localX/Y
运动图像来看,既不稳定也不平滑,这导致了我的问题。
以下是我的工作代码,享受它:)
package {
import flash.display.Bitmap;
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.net.URLRequest;
import flash.text.TextField;
public class DragIssue extends Sprite {
private static const URL: String = "assets/m1.jpg";
private var self: DragIssue;
private var sprite: Sprite;
private var startPoint: Point;
private var offsetX: Number = 0;
private var offsetY: Number = 0;
public function DragIssue() {
self = this;
init();
loadImage();
}
protected function init(): void {
if (stage == null) {
this.addEventListener(Event.ADDED_TO_STAGE, on_addedToStage);
} else {
stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
}
function on_addedToStage(event: Event): void {
self.removeEventListener(Event.ADDED_TO_STAGE, on_addedToStage);
stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
}
}
public function loadImage(): void {
var loader: Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
loader.load(new URLRequest(URL));
function imageLoaded(event: Event): void {
var bitmap: Bitmap = event.target.content as Bitmap;
self.sprite = new Sprite();
sprite.addChild(bitmap);
self.addChild(sprite);
sprite.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
sprite.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
}
}
private function onMouseMove(event: MouseEvent): void {
if (startPoint) {
sprite.x = offsetX + event.stageX - startPoint.x;
sprite.y = offsetY + event.stageY - startPoint.y;
}
}
private function onMouseUp(event: MouseEvent): void {
startPoint = null;
offsetX = sprite.x;
offsetY = sprite.y;
}
private function onMouseDown(event: MouseEvent): void {
startPoint = new Point(event.stageX, event.stageY);
}
}
}