Hi! I’m making a sort-of 2D platformmer where you must drag certain GameObjects with the mouse to get through. I’ve got a script that allows this to happen, except for one problem. When you drag an object, it seems to try to snap to the centre of the screen, and it does not move exactly with the mouse. Instead, the object requires more mouse movement than it should. If this is hard to explain, you can try out this script:
var normalCollisionCount = 1;
var moveLimit = .5;
var collisionMoveFactor = .01;
var addHeightWhenClicked = 0.0;
var freezeRotationOnDrag = true;
var cam : Camera;
private var myRigidbody : Rigidbody;
private var myTransform : Transform;
private var canMove = false;
private var zPos : float;
private var gravitySetting : boolean;
private var freezeRotationSetting : boolean;
private var sqrMoveLimit : float;
private var collisionCount = 0;
private var camTransform : Transform;
function Update () {
transform.rotation = Quaternion.identity;
}
function Start () {
myRigidbody = rigidbody;
myTransform = transform;
if (!cam) {
cam = Camera.main;
}
if (!cam) {
Debug.LogError("Can't find camera tagged MainCamera");
return;
}
camTransform = cam.transform;
sqrMoveLimit = moveLimit * moveLimit; // Since we're using sqrMagnitude, which is faster than magnitude
}
function OnMouseDown () {
canMove = true;
myTransform.Translate(Vector3.forward*addHeightWhenClicked);
gravitySetting = myRigidbody.useGravity;
freezeRotationSetting = myRigidbody.freezeRotation;
myRigidbody.useGravity = false;
myRigidbody.freezeRotation = freezeRotationOnDrag;
zPos = myTransform.position.z;
}
function OnMouseUp () {
canMove = false;
myRigidbody.useGravity = gravitySetting;
myRigidbody.freezeRotation = freezeRotationSetting;
if (!myRigidbody.useGravity) {
myTransform.position.z = zPos-addHeightWhenClicked;
}
}
function OnCollisionEnter () {
collisionCount++;
}
function OnCollisionExit () {
collisionCount--;
}
function FixedUpdate () {
if (!canMove) return;
myRigidbody.velocity = Vector3.zero;
myRigidbody.angularVelocity = Vector3.zero;
myTransform.position.z = zPos;
var mousePos = Input.mousePosition;
var move = cam.ScreenToWorldPoint(Vector3(mousePos.x, mousePos.y, camTransform.position.y - myTransform.position.z)) - myTransform.position;
move.z = 0.0;
if (collisionCount > normalCollisionCount) {
move = move.normalized*collisionMoveFactor;
}
else if (move.sqrMagnitude > sqrMoveLimit) {
move = move.normalized*moveLimit;
}
myRigidbody.MovePosition(myRigidbody.position + move);
}
@script RequireComponent(Rigidbody)
Can anyone tell me what I should add to the script in order to get it to work properly?
Here’s the game if you wanna see what’s the problem: http://biendeo.webs.com/WebPlayer.html
EDIT: I tried this same script, but using an orthographic perspective in the camera, and it works fine (although these draggable objects seem to go through the platform). Hopefully that’ll help too.