I am using Unity3d and I have Vector3.Lerp problem. In my initial code Lerp code working normal, but the second Lerp in PrevView method is not working correctly. Camera just shakes and returns to it's previous position. Where am I making mistake?
Code here:
using UnityEngine;
using System.Collections;
public class MoveCamera : MonoBehaviour
{
Vector3 camPos;
Vector3 startPos; // for storing Camera's first position
Transform camTr;
float speed = 5f;**strong text**
void Start()
{
camTr = Camera.main.transform;
camPos = camTr.position;
startPos = camTr.position;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit) && hit.collider.tag == "Buildings")
{
var buildings = GameObject.FindGameObjectsWithTag("Buildings");
foreach (GameObject go in buildings)
{
if (go == hit.collider.gameObject)
{
camPos.x = go.transform.position.x;
//camPos.y = go.transform.position.y + 30;
camPos.z = go.transform.position.z - 20;
}
else
{
go.SetActive(false);
}
}
}
}
camTr.position = Vector3.Lerp(camTr.position, camPos, Time.deltaTime * speed);
}
public void PrevView()
{
camTr.position = Vector2.MoveTowards(camTr.position, startPos, Time.deltaTime * speed);
}
}
I solved the problem. Many thanks for trying help me
My code here:
using UnityEngine;
using System.Collections;
public class MoveCamera : MonoBehaviour
{
Ray ray;
RaycastHit hit;
Vector3 camPos;
Vector3 startPos; // for storing Camera's first position
Transform camTr;
float speed = 2.5f;
bool b; // avoiding
void Start()
{
b = true;
camTr = Camera.main.transform;
camPos = camTr.position;
startPos = camTr.position;
}
void Update()
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit) && Input.GetMouseButtonDown(0))
{
if (hit.collider.tag == "Buildings")
{
var buildings = GameObject.FindGameObjectsWithTag("Buildings");
foreach (GameObject go in buildings)
{
if (go == hit.collider.gameObject)
{
camPos.x = go.transform.position.x;
camPos.y = go.transform.position.y + 30;
camPos.z = go.transform.position.z - 20;
}
else
{
go.SetActive(false);
}
}
}
}
if (b)
{
camTr.position = Vector3.Lerp(camTr.position, camPos, Time.deltaTime * speed);
}
}
public void PrevView()
{
b = false;
StartCoroutine("MoveBack");
}
IEnumerator MoveBack()
{
while ((camTr.position - startPos).sqrMagnitude > 0.01)
{
camTr.position = Vector3.MoveTowards(camTr.position, startPos, Time.deltaTime * speed * 10);
yield return new WaitForSeconds(0.001f);
}
}
}