Skip to content

Instantly share code, notes, and snippets.

@seferciogluecce
Last active December 19, 2023 13:26
Show Gist options
  • Save seferciogluecce/132e136ed71834143100f14b9b86b9fa to your computer and use it in GitHub Desktop.
Save seferciogluecce/132e136ed71834143100f14b9b86b9fa to your computer and use it in GitHub Desktop.
Mouse Drag 3d Objects in Unity, Tutorial at Devsplorer at https://youtu.be/bK5kYjpqco0
using System;
using UnityEngine;
[RequireComponent(typeof(Collider))]
public class Move3D : MonoBehaviour
{
private Camera mainCamera;
private float CameraZDistance;
void Start()
{
mainCamera = Camera.main;
CameraZDistance =
mainCamera.WorldToScreenPoint(transform.position).z; //z axis of the game object for screen view
}
private float counter = 0;
void OnMouseDrag()
{
Vector3 ScreenPosition =
new Vector3(Input.mousePosition.x, Input.mousePosition.y, CameraZDistance); //z axis added to screen point
Vector3 NewWorldPosition =
mainCamera.ScreenToWorldPoint(ScreenPosition); //Screen point converted to world point
transform.position = NewWorldPosition;
}
}
@treblalbert
Copy link

Is there any way to add it some sort of delay to the movement, so it feels more natural??

@okthenwhateverdude
Copy link

Is there any way to add it some sort of delay to the movement, so it feels more natural??

hey it's 2 years late and you probably don't care but I would imagine you would want to update the position of the object to the position defined in OnMouseDrag() through an update method using a percent of the difference between the two transform.position values

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment