2012-05-27 56 views
1

我正在使用Unity3D創建一個基於購物的遊戲。在我的遊戲中,我的物品沿着傳送帶走,然後他們必須拿起並用鼠標將其扔進購物車。到目前爲止,我可以讓鼠標去挑選物品,但是我怎麼去讓它們把它扔向一個特定的方向。我也需要做出這麼鼠標不能拖到房間裏的比賽是在邊界以外的對象用鼠標扔物體

我到目前爲止的代碼是:

#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); 
} 

詹姆斯

+0

我知道這個問題很老,但你可以發佈你的最後一個腳本嗎?我想達到同樣的效果 –

+0

那麼我的代碼是在上面,但我會嘗試找到下面提出的更改的副本。 –

回答

1

嘗試使用rigidbody.MovePosition()設置位置。這應該檢測與世界的碰撞。

我還沒有測試過你的代碼,但我認爲在OnMouseUp()中設置剛體速度而不是增加一個力可能更合適。

請記住這些都應該在FixedUpdate()中執行,所以也許您應該在事件方法中設置標誌。

+0

謝謝:)尋求幫助 –

3

我在四處移動捕捉鼠標位置並加快計算速度,並使事情奏效。我還添加了一個速度變量並將其乘以-1以使事情朝着正確的方向前進。

`#pragma strict 

var screenPoint:Vector3; 
var offset:Vector3; 

private var oldMouse:Vector3; 
private var mouseSpeed:Vector3; 
var speed = new int(); 

function Start(){ 
//oldMouse = Vector3.zero; 
} 

function Update(){ 
//mouseSpeed = oldMouse - Input.mousePosition; 
//oldMouse = Input.mousePosition; 
} 

function OnMouseDown() 
{ 
    oldMouse = Input.mousePosition; 
    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(){ 
mouseSpeed = oldMouse - Input.mousePosition; 
rigidbody.AddForce(mouseSpeed * speed * -1, ForceMode.Force); 
//rigidbody.AddForce(mouseSpeed*Time.deltaTime, ForceMode.Force); 
}