Advertisement
  1. Code
  2. ActionScript

Consejo rapido: cómo detectar la dirección del ratón mediante ActionScript

Scroll to top
Read Time: 4 min

Spanish (Español) translation by Santiago Diaz (you can also view the original English article)

En este consejo rápido, aprenderás cómo obtener la dirección actual del ratón en tu aplicación Flash usando AS3. Podrías usar esto para crear un método de control interesante para un juego, usando un ratón como un palanca de mando, por ejemplo. Por ahora, solo mostraremos la dirección en la pantalla.


Avance

Aquí hay un ejemplo rápido para demostrar en qué estamos trabajando:


Breve descripción

Usando un evento MouseEvent.MOUSE_MOVE monitorearemos el movimiento del cursor del ratón, almacenaremos los datos en variables y mostraremos su dirección actual.


Paso 1: crea un archivo nuevo

Abre Flash y crea un nuevo archivo Flash (ActionScript 3).


Paso 2: Abre el panel de acciones

Presiona Opción + F9, o ve a Ventana > Acciones para abrir el Panel de acciones.


Paso 3: Variables

Ingresa las variables que usaremos; sus nombres se explican por sí mismos:

1
var previousX:Number = 0;
2
var previousY:Number = 0;
3
var currentX:Number = 0;
4
var currentY:Number = 0;
5
var xDir:String;
6
var yDir:String;
7
var dir:TextField = new TextField();

Paso 4: función principal

Esta es la función principal:

1
function getMouseDirection():void
2
{
3
	dir.width = stage.stageWidth; //Size of the textfield

4
	addChild(dir); //Adds the textfield to the stage

5
6
   //Adds a mouse move listener to the stage and executes the checkDirection function when a mouse movement occurs

7
	stage.addEventListener(MouseEvent.MOUSE_MOVE, checkDirection);
8
}

Paso 5: Verifica la dirección

Este código llama a las funciones que verifican la dirección y muestra el resultado en el escenario TextField.

1
function checkDirection(e:MouseEvent):void
2
{
3
	getHorizontalDirection();
4
	getVerticalDirection();
5
	
6
	dir.text = "x: " + xDir + ", y: " + yDir;
7
}

Paso 6: Obtén direcciones

Verifica las direcciones del ratón.

1
//Horizontal

2
function getHorizontalDirection():void
3
{
4
	previousX = currentX; //Checks the last position

5
	currentX = stage.mouseX; //Gets the current position

6
7
	if (previousX > currentX) //Compares both positions to determine the direction

8
	{
9
		xDir = "left";
10
	}
11
	else if (previousX < currentX)
12
	{
13
		xDir = "right";
14
	}
15
	else
16
	{
17
		xDir = "none";
18
	}
19
}
20
21
//Vertical

22
function getVerticalDirection():void
23
{
24
	previousY = currentY; //Checks the last position

25
	currentY = stage.mouseY; //Gets the current position

26
27
	if (previousY > currentY) //Compares both positions to determine the direction

28
	{
29
		yDir = "up";
30
	}
31
	else if (previousY < currentY)
32
	{
33
		yDir = "down";
34
	}
35
	else
36
	{
37
		yDir = "none";
38
	}
39
}

Paso 7: ejecuta la función

Para iniciar la función, agrega esta línea al código. Una vez que se ejecuta la función getMouseDirection(), configurará el detector de eventos MOUSE_MOVE que alimenta el indicador de dirección.

1
getMouseDirection();

Paso 8: Versión de la clase de documento

1
package
2
{
3
	import flash.display.MovieClip;
4
	import flash.text.TextField;
5
	import flash.events.MouseEvent;
6
	
7
	public class MouseMoveDemo extends MovieClip
8
	{
9
		public var previousX:Number = 0;
10
		public var previousY:Number = 0;
11
		public var currentX:Number = 0;
12
		public var currentY:Number = 0;
13
		public var xDir:String;
14
		public var yDir:String;
15
		public var dir1:TextField = new TextField();
16
		public var dir2:TextField = new TextField();
17
		
18
		public function MouseMoveDemo()
19
		{
20
			getMouseDirection();
21
		}
22
		
23
		public function getMouseDirection():void
24
		{
25
			dir1.width = stage.stageWidth;
26
			addChild(dir1);
27
			dir2.width = stage.stageWidth;
28
			dir2.y = 50;
29
			addChild(dir2);
30
			stage.addEventListener(MouseEvent.MOUSE_MOVE, checkDirection);
31
		}
32
		
33
		public function checkDirection(e:MouseEvent):void
34
		{
35
			getHorizontalDirection();
36
			getVerticalDirection();
37
			
38
			dir1.text = "x: " + xDir
39
			dir2.text = "y: " + yDir;
40
		}
41
		
42
		public function getHorizontalDirection():void
43
		{
44
			previousX = currentX;
45
			currentX = stage.mouseX;
46
			
47
			if (previousX > currentX)
48
			{
49
				xDir = "left";
50
			}
51
			else if (previousX < currentX)
52
			{
53
				xDir = "right";
54
			}
55
			else
56
			{
57
				xDir = "none";
58
			}
59
		}
60
		
61
		public function getVerticalDirection():void
62
		{
63
			previousY = currentY;
64
			currentY = stage.mouseY;
65
66
			if (previousY > currentY)
67
			{
68
				yDir = "up";
69
			}
70
			else if (previousY < currentY)
71
			{
72
				yDir = "down";
73
			}
74
			else
75
			{
76
				yDir = "none";
77
			}
78
		}
79
80
	}
81
	
82
}

Opta por este enfoque si prefieres utilizar una clase de documento en lugar de un código de línea de tiempo. Lee este consejo rápido si no estás seguro de qué hacer con él.

Puedes usar esta clase para incrustar un indicador de dirección del ratón dentro de cualquier proyecto. Simplemente copia toda la clase en un nuevo archivo AS, guárdalo como "MouseMoveDemo.as", luego podrá hacer referencia a él usando el siguiente fragmento:

1
var mouseMoveDemo:MouseMoveDemo = new MouseMoveDemo();
2
addChild( mouseMoveDemo );

Conclusión

Este es un ejemplo básico de cómo puedes utilizar dicha función; ¡Pruébalo, experimenta y utilízalo en tus propios proyectos!

Gracias por leer.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.