让物体跟随鼠标移动
定义变量
[HideInInspector]
public bool isPressed, isBallThrown;
[HideInInspector]
public Transform currentBall = null;
private Vector3 mouseStartPos;
private Vector3 mouseEndPos;
void Update()
{
if (Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1000f, 1 << 0))
{
if (hit.transform.tag == "Basketball"&&!isPressed)
{
isPressed = true;
currentBall = hit.transform;
ballRigidbody = currentBall.GetComponent<Rigidbody>();
ballRigidbody.isKinematic = true;
mouseStartPos = Input.mousePosition;
}
}
if (currentBall != null)
{
Vector3 mousePos = Input.mousePosition;
mousePos.z = 18.5f;
worldPos.x = Camera.main.ScreenToWorldPoint(mousePos).x;
if (worldPos.x >= bgCamera.ViewportToWorldPoint(new Vector2(1, 0)).x - 0.4f)
{
worldPos.x = bgCamera.ViewportToWorldPoint(new Vector2(1, 0)).x - 0.4f;
}
if (worldPos.x <= bgCamera.ViewportToWorldPoint(new Vector2(0, 0)).x + 0.4f)
{
worldPos.x = bgCamera.ViewportToWorldPoint(new Vector2(0, 0)).x + 0.4f;
}
worldPos.z = Camera.main.ScreenToWorldPoint(mousePos).z;
worldPos.y = Camera.main.ScreenToWorldPoint(mousePos).y;
currentBall.position = worldPos;
}
}
else if (Input.GetMouseButtonUp(0))
{
if (currentBall != null)
{
mouseEndPos = Input.mousePosition;
isPressed = false;
}
}
}