- Home /
Question by
MontyMomentum · Aug 10, 2020 at 09:06 AM ·
collisioncollidermousepositiondrag objects
Change script to make the object only movable in one direction and add collision
I have a script that makes an object drag-able with the mouse. How do I change this script to make the object only be movable in one direction (for example only the X value can be changed), and also adding collision so the object I'm moving can't phase through walls.
Here's the script
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(MeshCollider))]
public class GizmosController : MonoBehaviour
{
private Vector3 screenPoint;
private Vector3 offset;
void OnMouseDown()
{
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
void OnMouseDrag()
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
}
Comment
Your answer
Follow this Question
Related Questions
How to find out what is the closest point on a object? 0 Answers
Mouse Movement with physics 1 Answer
OnCollisionStay2D is ignoring OnCollisionEnter2D 2 Answers
Collision not working 1 Answer
Unwanted jittery behavior 2 Answers