Unitkiv
January 22, 2024, 11:34am
1
I’ve this script. I just put it in Main Camera. However, it doesn’t work:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMove : MonoBehaviour
{
private Vector3 Origin;
private Vector3 Difference;
private Vector3 resetCamera;
private bool drag = false;
private void Start()
{
resetCamera = Camera.main.transform.position;
}
// Update is called once per frame
private void LateUpdate()
{
if (Input.GetMouseButton(0))
{
Difference = (Camera.main.ScreenToWorldPoint(Input.mousePosition)) - Camera.main.transform.position;
if (drag == false)
{
drag = true;
Origin = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
else
{
drag = false;
}
if (drag)
{
Camera.main.transform.position = Origin - Difference;
}
if (Input.GetMouseButton(1))
{
Camera.main.transform.position = resetCamera;
}
}
}
}
If you have any idea, I’d be much appreciated.
Ryiah
January 22, 2024, 1:24pm
2
Lines 23 through 32 are setting the boolean one frame only to immediately clear it the next frame.
1 Like
I have a drag-camera and drag-world-object script that I keep here:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// @kurtdekker
//
// simple world drag: this object must have ONE collider on it
public class SimpleWorldDrag : MonoBehaviour
{
Plane plane;
Vector3 lastWorldPosition;
void Start()
{
plane = new Plane( inNormal: Vector3.up, inPoint: Vector3.zero);
}
bool dragging;
This file has been truncated. show original
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SimpleCameraDrag : MonoBehaviour
{
Plane plane;
Vector3 lastWorldPosition;
void Start()
{
plane = new Plane( inNormal: Vector3.up, inPoint: Vector3.zero);
}
void Update()
{
var touches = MicroTouch.GatherMicroTouches();
if (touches.Length == 1)
{
This file has been truncated. show original
Beyond that, remember that camera stuff is pretty tricky… you may wish to consider using Cinemachine from the Unity Package Manager.
There’s even a dedicated forum: Unity Engine - Unity Discussions
If you insist on making your own camera controller, the simplest way to do it is to think in terms of two Vector3 points in space: where the camera is LOCATED and where the camera is LOOKING.
private Vector3 WhereMyCameraIsLocated;
private Vector3 WhatMyCameraIsLookingAt;
void LateUpdate()
{
cam.transform.position = WhereMyCameraIsLocated;
cam.transform.LookAt( WhatMyCameraIsLookingAt);
}
Then you just need to update the above two points based on your GameObjects, no need to fiddle with rotations.
1 Like