When my game start it instantiates a number of balls. The player can select any of these balls and move them to a place. Now everything works OK. I can select any of the balls and move them with ASWD keys but only when the mouse is over a specific ball. Once it looses focus, it will disable the script that activated movement with ASWD keys. Is there a way, looking at the script below to make the AWSD keys independent from onMouseOver function()?
#pragma strict
private var screenPoint:Vector3 ;
private var offset:Vector3;
public var speed : float = 0.2;
function OnMouseDown() {
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
function OnMouseEnter() {
var curScreenPoint:Vector3 = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 6);
var curPosition:Vector3 = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
if (Input.GetKey("a"))
{
this.transform.position.x -= this.speed;
}
if (Input.GetKey("d"))
{
this.transform.position.x += this.speed;
}
if (Input.GetKey("w"))
{
this.transform.position.z += this.speed;
}
if (Input.GetKey("s"))
{
this.transform.position.z -= this.speed;
}
}
I’m assuming that all the object you want to move have this same script. Below is a solution. It has a ‘currTrans’ variable. This variable is ‘static’ which means that all the instances of this class will share the value. The OnMouseDown() code sets this variable to the transform of the object clicked on. The movement code has been moved into Update(). If the last clicked object is not the object with this script, then Update() just returns and no movement is done.
Note I’ve allso added ‘Time.deltaTime’ to your movement code so that movement will be frame rate independent.
#pragma strict
private var screenPoint:Vector3 ;
private var offset:Vector3;
public var speed : float = 3.0;
static private var currTrans : Transform = null;
function OnMouseDown() {
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
currTrans = transform;
}
function Update() {
if (currTrans != transform) return;
var curScreenPoint:Vector3 = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 6);
var curPosition:Vector3 = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
if (Input.GetKey("a"))
{
transform.position.x -= speed * Time.deltaTime;
}
if (Input.GetKey("d"))
{
transform.position.x += speed * Time.deltaTime;
}
if (Input.GetKey("w"))
{
transform.position.z += speed * Time.deltaTime;
}
if (Input.GetKey("s"))
{
transform.position.z -= speed * Time.deltaTime;
}
}