I’m making a 2.5D sidescroller game, and I need my character to face the direction he’s moving. My scene is setup so that Characters move forward and backward along the z axis, and up and down along the y axis.
So, In my current script I have managed to make my Character turn back and forth while he’s grounded. But when he jumps, he also turns to face up and down, because of the following piece of code (at least I think so):
if (Input.GetAxis("Horizontal"))
{
transform.LookAt(transform.position + moveDirection);
}
So, what do I need to add here to make the character only look at the moveDirection of z-axis?
Ps. I have a strong feeling that the problem might be that line, but I can post the whole script if you think the problem is elsewhere.
EDIT
So, here’s a little pic that shows how my scene is positioned, and how my character turned in the original script, while he was grounded.
The red capsule is the character, and the green thing is his gun, which points at the direction he’s facing.
And this is what happens if I jump:
I’m trying to make it turn in air just the same way as if it were grounded.
And just as a bonus, here’s my whole current script with your editings:
var speed : float = 20.0;
var jumpSpeed : float = 20.0;
var gravity : float = 30.0;
private var moveDirection : Vector3 = Vector3.zero;
function Update()
{
var controller : CharacterController = GetComponent(CharacterController);
var inputZ = Input.GetAxis("Horizontal");
if(Input.GetAxis("Horizontal"))
{
var tempDirection = moveDirection;
tempDirection.z = transform.position.z;
transform.LookAt(transform.position + tempDirection);
}
if (controller.isGrounded)
{
moveDirection = Vector3(0, 0, (Input.GetAxis("Horizontal")));
moveDirection *= speed;
if (Input.GetButton ("Jump"))
{
moveDirection.y = jumpSpeed;
}
}
else
{
moveDirection.z = inputZ * speed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}