【发布时间】:2021-10-08 16:46:14
【问题描述】:
所以对于我的游戏,我希望能够用我的光标拾取物体并扔掉它们。我可以自己进行拖放操作,但如果你扔掉它,我不知道如何让它抛出物体。如果你试图扔它,物体就会掉到地板上。有人能帮我吗?我尝试在网上查找,但找不到解决方案。代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DragAndDropObjects : MonoBehaviour
{
public bool canDrag = true;
public bool isDragging;
GameObject player;
Rigidbody2D rb;
void Start()
{
rb = gameObject.GetComponent<Rigidbody2D>();
player = GameObject.Find("Player");
}
void OnMouseDown()
{
if(canDrag && player.GetComponent<Movement>().draggingEnabled)
{
if(!isDragging)
{
print("start dragging");
isDragging = true;
rb.gravityScale = 0f;
gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeRotation;
player.GetComponent<Movement>().draggingObject = true;
GameObject[] heavyObjects = GameObject.FindGameObjectsWithTag("Heavy");
foreach (GameObject heavy in heavyObjects)
{
heavy.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.None;
}
}
}
}
void OnMouseUp()
{
if(isDragging)
{
isDragging = false;
rb.gravityScale = 1f;
gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.None;
player.GetComponent<Movement>().draggingObject = false;
print("stop dragging");
GameObject[] heavyObjects = GameObject.FindGameObjectsWithTag("Heavy");
foreach (GameObject heavy in heavyObjects)
{
heavy.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezePositionX;
}
}
}
void FixedUpdate()
{
Vector3 mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
if(isDragging)
{
transform.position = Vector2.Lerp(transform.position, mousePos, 1f);
if (Input.GetAxis("Mouse ScrollWheel") > 0f )
{
gameObject.transform.Rotate(0, 0, 10f);
}
else if (Input.GetAxis("Mouse ScrollWheel") < 0f )
{
gameObject.transform.Rotate(0, 0, -10f);
}
}
}
}
如果你有答案,请告诉我!谢谢!
【问题讨论】:
-
这也是统一的 2d