summaryrefslogtreecommitdiff
path: root/assets/javascripts/rectangles/engine/scenery/image.js
blob: 6434603b7213c1afbccca0d26ac3e0d519c499dd (plain)
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
Scenery.image = function (wall, img) {

	var base = this
	var center
	var x = 0, y = 0, z = 0, bounds
	var dragging = false

	// should be proportional to distance from wall
	var cursor_amp = 1.5
	
	base.init = function(){
		base.build()
		base.bind()
	}
	
	base.build = function(){
		center = wall.center_for(img)
		base.mx_img = new MX.Image({
			src: img.src,
			x: center.a,
			y: Rooms.list[wall.room].height/2 - img.height/2 - 20,
			z: center.b,
			scale: 300/img.naturalWidth,
			rotationY: wall_rotation[ wall.side ],
			backface: false,
		})
		scene.add( base.mx_img )
	}
	
	base.bind = function(){
		Scenery.mouse.bind_el(base.mx_img.el)
		Scenery.mouse.on("down", down)
		Scenery.mouse.on("enter", switch_wall)
		Scenery.mouse.on("drag", drag)
		Scenery.mouse.on("up", up)
	}

	function down (e, cursor){
		if (e.target != base.mx_img.el) return;
		dragging = true
		x = base.mx_img.x
		y = base.mx_img.y
		z = base.mx_img.z
		bounds = wall.bounds_for(img)
		document.body.classList.add("dragging")
	}
	
	function switch_wall (e, new_wall, cursor){
		if (! dragging) return
		if (new_wall.uid == wall.uid) return
		if (! new_wall.fits(img)) return

		bounds = new_wall.bounds_for(img)
		center = new_wall.center_for(img)

		x = center.a
		z = center.b
		
		var wall_group = wall.side | new_wall.side
		
		if (wall.side !== new_wall.side && wall_group !== FRONT_BACK && wall_group !== LEFT_RIGHT) {
			switch (wall.side) {
				case FRONT:
					z = bounds.x.a
					break
				case BACK:
					z = bounds.x.b
					break
				case LEFT:
					x = bounds.x.a
					break
				case RIGHT:
					x = bounds.x.b
					break
			}
		}

		cursor.x.a = cursor.x.b
		
		base.mx_img.move({
			x: x,
			z: z,
			rotationY: wall_rotation[ new_wall.side ]
		})
		
		wall = new_wall
	}
	
	function drag (e, cursor){
		if (! dragging) return
		
		base.mx_img.y = bounds.y.clamp( y - cursor.y.magnitude()*cursor_amp )
		switch (wall.side) {
			case FRONT:
				base.mx_img.x = bounds.x.clamp( x - cursor.x.magnitude()*cursor_amp )
				break
			case BACK:
				base.mx_img.x = bounds.x.clamp( x + cursor.x.magnitude()*cursor_amp )
				break
			case LEFT:
				base.mx_img.z = bounds.x.clamp( z + cursor.x.magnitude()*cursor_amp )
				break
			case RIGHT:
				base.mx_img.z = bounds.x.clamp( z - cursor.x.magnitude()*cursor_amp )
				break
		}
	}

	function up (e, cursor){
		dragging = false
		document.body.classList.remove("dragging")
	}
	
	return base
}