How do i move camera forward then have it go back?

Hey guys, ill try my best to explain, I also have a script here I use, I press ASD and the camera rotates a set angel.

I want to add so when I press W the camera will Move forward about 10 from its position instead of any rotation, an when I let go of the W key it goes back to its original spot, this way I can look left n right n back an have it swing back which is does already, but add so when I press W it just moves forward a little an then goes back…

Please Help :slight_smile:

Thanks heaps

using UnityEngine;
using System.Collections;

public class RotateCamera : MonoBehaviour {

	private Quaternion startingRotation;
	public float speed = 10;

	void Start(){
		//save the starting rotation
		startingRotation = this.transform.rotation;
	}

	void Update () {
		//return back to the starting rotation
		if( Input.GetKeyUp( KeyCode.D ) || Input.GetKeyUp( KeyCode.A ) || Input.GetKeyUp( KeyCode.S ) ){
			StopAllCoroutines();
			StartCoroutine(Rotate(0));
		}

		//go to 90 degrees with right arrow
		if( Input.GetKeyDown( KeyCode.D) ){
			StopAllCoroutines();
			StartCoroutine(Rotate(90));
		}

		//go to -90 degrees with left arrow
		if( Input.GetKeyDown( KeyCode.A ) ){
			StopAllCoroutines();
			StartCoroutine(Rotate(-90));
		}

		//go to -180 degrees with Back arrow
		if( Input.GetKeyDown( KeyCode.S ) ){
			StopAllCoroutines();
			StartCoroutine(Rotate(-180));
		}

	}

	IEnumerator Rotate(float rotationAmount){
		Quaternion finalRotation = Quaternion.Euler( 0, rotationAmount, 0 ) * startingRotation;

		while(this.transform.rotation != finalRotation){
			this.transform.rotation = Quaternion.Lerp(this.transform.rotation, finalRotation, Time.deltaTime*speed);
			yield return 0;
		}
	}
}

1 Answer

1

You can try something like this, using MoveTowards:

private Vector3 startingPosition;
private Vector3 startingForward;
private Quaternion startingRotation;
public float speed = 10;
public float distance = 10;

void Start ()
{
	startingForward = transform.forward;
	startingPosition = transform.position;
	//save the starting rotation
	startingRotation = this.transform.rotation;
}

…and in your Update function:

		//move forward when pressing W, move back on release
		if (Input.GetKey (KeyCode.W)) {
			transform.position = Vector3.MoveTowards (transform.position, startingPosition + startingForward * distance, speed * Time.deltaTime);
		} else if (transform.position != startingPosition) {
			transform.position = Vector3.MoveTowards (transform.position, startingPosition, speed * Time.deltaTime);
		}

Hope this helped!