Howdy, folks.
So, I’m attempting get my player object to be drag and droppable via the mouse. I’m doing this by allowing the object to translate based on a certain ratio between the mouse’s position on screen and the 3d space. When I run the script below it begins to work…but then crashes with a NullReferenceException error pointing to the line that translates the object in the script. It crashes when I move only a little ways away from the object’s origin…but until then it appears to work fine. Could it be because the object I’m trying to “drag” around has a rigidbody on it, and rigidbodies don’t like translation? I’m really kind of miffed as to why this is happening. If you can figure out this spooky mystery, I will proudly present you with the key to the city in front of a crowd of cheering citizens…
Thanks for your help, in advance!
–Simon
var pickedUpPlayer = false;
var originalMouseX = 0.000;
var originalMouseY = 0.000;
var deltaMouseX = 0.000;
var deltaMouseY = 0.000;
var screenRatio = 100.000;
function FixedUpdate () {
var hitOrigin : RaycastHit;
var rayOrigin = Camera.main.ScreenPointToRay (Input.mousePosition);
if ( Physics.Raycast( rayOrigin, hitOrigin, 100 ) && !pickedUpPlayer)
{
//detects if the player has been clicked on.
if (Input.GetMouseButton(0))
{
//if the user has clicked on the player tagged object, they can start to move him or her around via the next if statement...
//so we need to know at what point on the screen the player has clicked, such that in the next if statement we can determine
//the change in mouse position, and translate the player's transform accordingly.
if ( hitOrigin.collider.gameObject.renderer && hitOrigin.collider.gameObject.tag == "Player")
{
pickedUpPlayer = true;
originalMouseX = Input.mousePosition.x;
originalMouseY = Input.mousePosition.y;
}
}
}
//allows you to drag the player according to where the mouse is on the screen. The game knows that the distance the mouse moves onscreen
//coordinates to a certain distance that it is moving in the 3d space. since there is no z coordinate changed, this works.
if (pickedUpPlayer)
{
deltaMouseX = Mathf.Abs(Input.mousePosition.x) - Mathf.Abs(originalMouseX);
deltaMouseY = Mathf.Abs(Input.mousePosition.y) - Mathf.Abs(originalMouseY);
print("Delta X: " + deltaMouseX + ", Delta Y: " + deltaMouseY);
hitOrigin.collider.gameObject.transform.Translate(deltaMouseX / screenRatio, deltaMouseY / screenRatio, 0);
}
if (!Input.GetMouseButton(0) && pickedUpPlayer)
{
pickedUpPlayer = false;
print("Dropped the player");
}
}
Format the code using the 101-010 button.
– WazOrder expressions such that cheapest is left of &&, not right of, as it short-circuits.
– WazWhich city are you mayor of exactly?
– Waz