How do I make the object being dragged respect the colliders of my game’s borders? Right now I can simply drag the object through them. It does seem that it detects the collision when i put a debug.log in a OnCollisionEnter void, but to no avail. Heres the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DragObject : MonoBehaviour
{
private float mZCoord;
private Vector3 mOffset;
private Vector3 lastMousePosition;
private Vector3 velocity;
float flingPowerScale = 0.33f;
private Rigidbody rb;
private void Start()
{
rb = GetComponent<Rigidbody>();
if (rb == null)
{
Debug.LogError("No Rigidbody found on the object. Please attach a Rigidbody.");
}
}
private void OnMouseDown()
{
mZCoord = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
// Store offset = gameobject mouse pos - mouse world pos
mOffset = gameObject.transform.position - GetMouseWorldPos();
// Initialize the last mouse position
lastMousePosition = GetMouseWorldPos();
}
void OnMouseDrag()
{
Vector3 currentMousePosition = GetMouseWorldPos();
// Calculate velocity based on the difference between current and last mouse positions
velocity = (currentMousePosition - lastMousePosition) / Time.deltaTime;
// Update position based on mouse drag
Vector3 newPosition = currentMousePosition + mOffset;
// Apply the clamped position
rb.MovePosition(newPosition);
// Update last mouse position
lastMousePosition = currentMousePosition;
}
private void OnMouseUp()
{
// When the mouse is released, apply the calculated velocity to the Rigidbody
if (rb != null)
{
rb.velocity = velocity * flingPowerScale;
}
}
private Vector3 GetMouseWorldPos()
{
// pixel coordinates (x,y)
Vector3 mousePoint = Input.mousePosition;
// z coordinate of gameobject on screen
mousePoint.z = mZCoord;
return Camera.main.ScreenToWorldPoint(mousePoint);
}
}