I am using Unity3D to create a shopping based game. In my game I have my objects go along a conveyer belt which they then have to pick up and throw using the mouse into a shopping trolley. So far I can get the mouse to pick the items up but how would I go about letting them throw it a particular direction. I also need to make it so the mouse cannot drag an object outside of the boundaries of the room the game is in.
The code I have so far is:
#pragma strict
var screenPoint:Vector3;
var offset:Vector3;
private var oldMouse:Vector3;
private var mouseSpeed:Vector3;
function Start(){
oldMouse = Vector3.zero;
}
function Update(){
mouseSpeed = oldMouse - Input.mousePosition;
oldMouse = Input.mousePosition;
}
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 OnMouseDrag()
{
var curScreenPoint:Vector3 = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
var curPosition:Vector3 = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
function OnMouseUp(){
rigidbody.AddForce(mouseSpeed*Time.deltaTime, ForceMode.Force);
}
James
Try setting the position with rigidbody.MovePosition(). This should detect collisions with the world.
I haven’t tested your code yet, but I think it could be more appropriate to set the rigidbody’s velocity in OnMouseUp(), rather than adding a force.
Keep in mind both of these should be performed in FixedUpdate(), so perhaps you should set flags in the event methods.