我是Unity 2D的新手,我想强行拖动和扔掉我的游戏对象。基本上,我有三个游戏对象,当我将任何人拖离然后向上时,我应该向该方向强行掷出。
谁能告诉我该怎么做?
我已经尝试过此代码,但是当我要单击以拖动我的游戏对象时,它将直接引发而不拖动它。
这是我的代码
private Rigidbody2D rb;
private float jumpForce = 700f;
private bool jumpAllowed = false;
float deltaX, deltaY;
string button_name = "";
// Use this for initialization
private void Start ()
{
Debug.Log("Started");
rb = GetComponent<Rigidbody2D> ();
PhysicsMaterial2D mat = new PhysicsMaterial2D();
mat.bounciness = 0.75f;
mat.friction = 0.4f;
GetComponent<CircleCollider2D>().sharedMaterial = mat;
}
// Update is called once per frame
private void Update ()
{
Debug.Log("Update");
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
Vector2 touchPos = Camera.main.ScreenToWorldPoint(touch.position);
switch (touch.phase)
{
case TouchPhase.Began:
if (GetComponent<Collider2D>() == Physics2D.OverlapPoint(touchPos))
{
deltaX = touchPos.x - transform.position.x;
deltaY = touchPos.y - transform.position.y;
jumpAllowed = true;
rb.freezeRotation = true;
rb.velocity = new Vector2(0, 0);
rb.gravityScale = 0;
GetComponent<Collider2D>().sharedMaterial = null;
}
break;
case TouchPhase.Moved:
if (GetComponent<Collider2D>() == Physics2D.OverlapPoint(touchPos) && jumpAllowed)
{
rb.MovePosition(new Vector2(touchPos.x - deltaX, touchPos.y - deltaY));
}
break;
case TouchPhase.Ended:
jumpAllowed = false;
rb.freezeRotation = false;
rb.gravityScale = 2;
PhysicsMaterial2D mat = new PhysicsMaterial2D();
mat.bounciness = 0.75f;
mat.friction = 0.4f;
GetComponent<CircleCollider2D>().sharedMaterial = mat;
break;
}
}
}
首先,有一个错误
rb.MovePosition(new Vector2(touchPos.x - deltaX, touchPos.y - deltaY));
应该
rb.MovePosition(new Vector2(touchPos.x + deltaX, touchPos.y + deltaY));
还有另一个问题,MovePosition
根本不影响物体速度。如果您停止使用MovePosition
,则该对象将掉落而不会保留前一动作的任何能量。
您只需存储每个动作的前一个位置,然后在上执行此操作TouchPhase.Ended
:
rb.velocity = (rb.position - prevPosition) / Time.deltaTime;
简而言之,这将计算完成最后一个运动所需的速度,并将其应用于刚体。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句