forked from sorenbs/MoveTo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
moveto.js
78 lines (68 loc) · 2.14 KB
/
moveto.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
///1.8
Crafty.c("MoveTo", {
_speed: 2,
_onmousedown:function (e) {
this._target = { x: e.realX, y: e.realY };
var dx = e.realX - this.x, dy = e.realY - this.y;
this._movement={
x:(dx * this._speed) / (Math.sqrt(dx * dx + dy * dy)),
y:(dy * this._speed) / (Math.sqrt(dx * dx + dy * dy))
},
this.trigger('NewDirection', this._movement);
},
init: function () {
this.requires("Mouse");
Crafty.addEvent(this, Crafty.stage.elem, "mousedown", this._onmousedown);
/*
this.bind('NewDirection', function(arg) {
alert('NewDirection is called');
}
);
*/
var norm=function(x, y) {
absx=Math.abs(x);
absy=Math.abs(y);
if(absx>absy) {
max=absx;
min=absy;
} else {
max=absy;
min=absx;
}
return max*Math.sqrt(1+Math.pow(min/max,2));
};
this.bind("EnterFrame", function () {
/*
document.getElementById('x').innerHTML=this.x;
document.getElementById('y').innerHTML=this.y;
if(this._target) {
document.getElementById('targetx').innerHTML=this._target.x;
document.getElementById('targety').innerHTML=this._target.y;
}
*/
if (this.disableControls || !this._target) return;
if (norm(this._target.x - this.x, this._target.y - this.y) < this._speed) {
var prev_pos = {
x:this.x,
y:this.y
}
this._movement={
x:this._target.x - this.x,
y:this._target.y - this.y
};
this.x=this._target.x;
this.y=this._target.y;
this._target=undefined;
this.trigger('Moved', this.prev_pos);
}
if (this._movement.x !== 0) {
this.x += this._movement.x;
this.trigger('Moved', { x: this.x - this._movement.x, y: this.y });
}
if (this._movement.y !== 0) {
this.y += this._movement.y;
this.trigger('Moved', { x: this.x, y: this.y - this._movement.y });
}
});
}
});