用鼠标投掷对象

时间:2012-05-27 09:52:28

标签: unity3d

我使用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);
}

詹姆斯

2 个答案:

答案 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);
}

答案 1 :(得分:1)

尝试使用rigidbody.MovePosition()设置位置。这应该可以检测到与世界的碰撞。

我还没有测试过您的代码,但我认为在OnMouseUp()中设置刚体的速度可能更合适,而不是添加力。

请记住,这些都应该在FixedUpdate()中执行,所以也许你应该在事件方法中设置标志。