如何在Unity2D中强制拖放对象 [英] How to Drag and throw object forcefully in Unity2D
问题描述
我是Unity 2D的新手,我想拖动&强行扔掉我的游戏对象.基本上,我有三个游戏对象,当我将任何人拖离然后向上时,我应该向该方向强行抛掷.
I'm new in Unity 2D i want to drag & throw my game object forcefully. basically i have three game object and when i drag anyone off then to upward i should be throw forcefully on that direction.
谁能告诉我该怎么做?
我已经尝试过此代码,但是当我要单击以拖动游戏对象时,它会直接引发而不拖动它.
i have tried this code but when i'm going to click to drag my game object then it throws directly without dragging it.
这是我的代码
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
,则该对象将掉落而不会保留前一动作的任何能量.
There's also another issue, MovePosition
doesn't affect the object velocity at all. If you stop using MovePosition
, the object will just fall without keeping any energy from the previous movement.
您可以简单地存储每个动作的前一个位置,并在TouchPhase.Ended
上执行此操作:
You could simply store the previous position every movement, and do this on TouchPhase.Ended
:
rb.velocity = (rb.position - prevPosition) / Time.deltaTime;
简单地说,这将计算完成最后一个运动所需的速度,并将其应用于刚体.
Simply put, this calculates the velocity that was required to accomplish the last movement, and apply it to the rigidbody.
这篇关于如何在Unity2D中强制拖放对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!