【问题标题】:How to add velocity to drag and drop?如何为拖放添加速度?
【发布时间】: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

标签: c# unity3d 2d physics


【解决方案1】:

这样做的方法是使用RigidBody2D.velocity 获取对象速度并将其添加到对象变换中。您也可以将速度乘以 Time.deltaTime 以使飞行过程更顺畅。

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 2017-06-23
  • 1970-01-01
  • 2018-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-03
相关资源
最近更新 更多