Search code examples
c#visual-studiounity-game-engine

Drag&Drop System - Object is Shaking Problem


I have a code; it's basically a Drag&Drop system. However, I noticed that when I drag some objects, they shake while moving. This is quite frustrating because it affects the user experience. Can you give me some ideas on how to fix this? Please help me; I'm starting to feel really desperate. I often hit roadblocks when coding, and I truly need some assistance with this issue. It has become very complex, so fxck chatgpt.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Collider))]
[RequireComponent(typeof(Rigidbody))] // Rigidbody bileşenini ekliyoruz
public class DragDrop : MonoBehaviour
{
private Vector3 mouseOffset;
private Camera mainCamera;
private float zDistance;
private Rigidbody rb; // Rigidbody referansı

private void Awake()
{
    mainCamera = Camera.main;
    rb = GetComponent<Rigidbody>(); // Rigidbody'yi alıyoruz
    rb.isKinematic = true; // Başlangıçta kinematic yapıyoruz
}

private void OnMouseDown()
{
    // Z mesafesini tıklama anında belirliyoruz
    zDistance = Vector3.Distance(mainCamera.transform.position, transform.position);
    mouseOffset = Input.mousePosition - mainCamera.WorldToScreenPoint(transform.position);

    rb.isKinematic = true; // Sürükleme sırasında fizik motorunun müdahale etmemesi için kinematic yapıyoruz
}

private void OnMouseDrag()
{
    Vector3 mousePosition = Input.mousePosition - mouseOffset;
    mousePosition.z = zDistance; // Z değerini ayarlıyoruz
    Vector3 worldMousePos = mainCamera.ScreenToWorldPoint(mousePosition);

    // Fiziksel hareketle taşımak için Rigidbody.MovePosition kullanıyoruz
    rb.MovePosition(worldMousePos);

    // Rotasyonu sabit tutmak için
    rb.rotation = Quaternion.Euler(0f, rb.rotation.eulerAngles.y, 0f); // Y ekseninde mevcut rotayı koruyoruz
}

private void OnMouseUp()
{
    rb.isKinematic = false; // Sürükleme bittiğinde fizik motorunun devreye girmesini sağlıyoruz
}

private void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.CompareTag("Player"))
    {
        Physics.IgnoreCollision(collision.collider, GetComponent<Collider>());
    }
}

private void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Player"))
    {
        Physics.IgnoreCollision(other, GetComponent<Collider>());
    }
}
}

Solution

  • At first clear whole methods related to drag n drop in code. You have to use 3 interfaces to create system: IBeginDragHandler, IEndDragHandler, IDragHandler. Then ensure interface methods and make Drag n Drop using eventData option. There are a lot of guides to Drag n Drop system you can check it out