Click Move Camera

Hi,

I’m new to Unity and C#, although I’ve scripted quite a bit in Neverwinter Nights (C++ based). The difference is actually surprising, and I’m having trouble with basic camera movement after having spent a few hours on it looking up tutorials and searching here.

using UnityEngine;
using System.Collections;

public class CameraMovement : MonoBehaviour 
{
	//private Vector3 vCameraSlideFrom;
	private Vector3 vCameraSlideTo;
	public float fSmooth;

	//{}
	// Update is called once per frame
	void Update () 
	{
		if(Input.GetKeyDown(KeyCode.Mouse0))
		{
			Ray rMouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
			RaycastHit rMouseRayHit;

			if(Physics.Raycast(rMouseRay, out rMouseRayHit, 50.0f))
			{
				Debug.DrawLine(rMouseRay.origin, rMouseRayHit.point);
				Debug.Log(rMouseRayHit.point);

				//vCameraSlideFrom = transform.position; //Camera.main.gameObject.transform.position;
				vCameraSlideTo = rMouseRayHit.point;
				
				transform.position = Vector3.Lerp(transform.position, vCameraSlideTo, fSmooth * Time.deltaTime);
			}
		}
	}
}

Basically I am going for a top-down view where you just click to move camera (smoothly - hence the lerping) to the clicked point. The Debug is returning a vector in the console but for whatever reason that is not being set as the new camera’s position.

Any help is appreciated. Thanks!

The line that makes things move:

 transform.position = Vector3.Lerp(transform.position, vCameraSlideTo, fSmooth * Time.deltaTime);

…is inside of your Input.GetKeyDown(). That means it will only be executed for the single frame where the key went down. One fix is to move that line outside the ‘if’ statement and execute it every frame. Insert it between lines 29 and 30.