- Home /
Drag Camera only when raycasting Terrain
Hey! I have a Simple Draggable Camera Script
using UnityEngine;
using System.Collections;
public class ViewDrag : MonoBehaviour {
Vector3 hit_position = Vector3.zero;
Vector3 current_position = Vector3.zero;
Vector3 camera_position = Vector3.zero;
float z = 0.0f;
// Use this for initialization
void Start () {
}
void Update(){
if(Input.GetMouseButtonDown(0)){
hit_position = Input.mousePosition;
camera_position = transform.position;
}
if(Input.GetMouseButton(0)){
current_position = Input.mousePosition;
LeftMouseDrag();
}
}
void LeftMouseDrag(){
current_position.z = hit_position.z = camera_position.y;
Vector3 direction = Camera.main.ScreenToWorldPoint(current_position) - Camera.main.ScreenToWorldPoint(hit_position);
// Invert direction to that terrain appears to move with the mouse.
direction = direction * -1;
Vector3 position = camera_position + direction;
transform.position = position;
}
}
and i wanted to ask, how can i change the script in a way, that it is only reacting, when the mouse is hitting the layer "Floor"?
my problem is that i have this draggable camera script and a NGUI scroll panel in my game. so every time i drag the scroll panel, the whole world/camera is also dragging
Answer by karma0413 · May 31, 2015 at 11:46 AM
I believe the function you seek is Physics.Raycast
http://docs.unity3d.com/ScriptReference/Physics.Raycast.html
One of the variables you can use in the RayCast statement is filtering it through layers... http://docs.unity3d.com/Manual/Layers.html
So from a design perspective, I would:
--put my UI on a new layer called "UI"
--put my Terrain on a new layer called "Terrain"
--Determine if mousebuttondown(0) == true
--if it is true, then use the physics.raycast to cast a ray from the camera to the 3dworld space, but also using the filter settings to check for BOTH: UI and Terrain
Now define it a little further..........
--if the out HitInfo.collider.gameObject.layer was the UI layer - then only adjust the scrolling UI
--if the out HitInfo.collider.gameObject.layer was the terrain layer - then use your camera dragging code
Let me know if you have confusion in setting up LayerMask or the Physics.Raycast code....
Your answer
![](https://koobas.hobune.stream/wayback/20220613142711im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
GameObject Moving Slow when drag with hand 0 Answers
Camera raycast and rotated collider 0 Answers
Make the terrain ignore Raycast if in between Camera and Player? 1 Answer
Raycast Object Selection 3 Answers
Help with Raycast on Render Texture 0 Answers