unity move forward code example
Example 1: unity movement on forward
transform.position += transform.forward * Time.deltaTime * movementSpeed;
Example 2: unity making object move forward without input
using UnityEngine; using System.Collections.Generic; public class BoatControl : MonoBehaviour { [Header("Values")] public Rigidbody boat; public KeyCode forwardMove; public KeyCode backwardMove; public KeyCode turnLeft; public KeyCode turnRight; public float boatSpeed; public float boatTurnSpeed; public float dampSpeed; public float dampTurning; [Header("Debug")] public float forwardVel; public float turnVel; void Update() { MoveShip (); TurnShip (); } void FixedUpdate() { boat.transform.position += transform.forward * (forwardVel * Time.deltaTime); boat.transform.Rotate (new Vector3 (0, turnVel, 0), Space.Self); } void MoveShip() { if (Input.GetKey (forwardMove)) { forwardVel = Mathf.Lerp (forwardVel, boatSpeed, (dampSpeed * Time.deltaTime)); } else if (Input.GetKey (backwardMove)) { forwardVel = Mathf.Lerp (forwardVel, -boatSpeed, (dampSpeed * Time.deltaTime)); } else { forwardVel = Mathf.Lerp (forwardVel, 0, (5 * Time.deltaTime)); } } void TurnShip() { if (Input.GetKey (turnLeft)) { turnVel = Mathf.Lerp (turnVel, -boatTurnSpeed, (dampSpeed * Time.deltaTime)); } else if (Input.GetKey (turnRight)) { turnVel = Mathf.Lerp (turnVel, boatTurnSpeed, (dampSpeed * Time.deltaTime)); } else { turnVel = Mathf.Lerp (turnVel, 0, (5 * Time.deltaTime)); } } }