using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Vector3 targetPos;
public float Xincrement;
public float speed;
public Rigidbody rb;
public float forwardForce = 2000f;
void FixedUpdate()
{
transform.position = Vector3.MoveTowards(transform.position, targetPos,speed*Time.deltaTime);
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if (Input.GetKey("left"))
{
targetPos = new Vector3(transform.position.x - Xincrement, transform.position.y, transform.position.z);
}
if (Input.GetKey("right"))
{
targetPos = new Vector3(transform.position.x + Xincrement, transform.position.y, transform.position.z);
}
}
}
You’re both changing transform.position and you’re adding force. It’s contradictory. Please explain what “going straight” means for you and take your time to try the tutorials like “Roll a ball”. You can find it in Unity Hub → Learn → Projects
“going straight” means i want to move cube along z axis on a ground of size (15,0.2,6000) and dodge obstacle(like cuboid ).