how to make constant movement on z axis via character controller. I need my character to constantly move forward at the same speed
CodePudding user response:
The forward axis of your character: transform.forward
Basic Solution with Transform
:
public float speed = 2f;
public void Update()
{
transform.position = transform.forward * (speed * Time.deltaTime);
}
Relative movement with Transform.Translate
;
transform.Translate(Vector3.forward * (speed * Time.deltaTime));
Basic Rigidbody velocity
Setter:
private Rigidbody rigidbody;
public void Start()
{
rigidbody = GetComponent<Rigidbody>();
}
public void Update()
{
rigidbody.velocity = transform.forward * speed;
}
CodePudding user response:
There are a couple ways of doing this. One is to simply move the object along the z axis via code with no care for physics. this will hold a constant velocity in that direction. You can hopefully see how this type of approach could e expanded for all directions by swapping out the zPosChange float for a vector representing the direction you want to move in. This is a kinematic position update.
public float speed = 10;
void Update()
{
float zPosUpdate = gameObject.transform.position.z
zPosUpdate = speed * Time.deltaTime;
gameObject.transform.position = new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, zPosUpdate );
}
The other way is to use the unity physics system to add force to a rigidbody component. To do this you must first have added a rigidbody and a collider to the object you are controlling. Since we want constant velocity and not acceleration and deceleration I wouldn't recommend that unless you really need the object to be able to be affected physically by collisions. You would do similar to the example I've given here but instead of the transform position you would set the velocity on the rigidbody component.
CodePudding user response:
You can use Add Force to you character.
character_Rigidbody.AddForce(transform.forward * speed);