I am working on a 3D platformer and I want the player to be able to move throughout the game play area as well as strafe back and forth while facing a direction and shooting. The problem is that the player will sometimes not face completely forward while strafing and shooting, sometimes the player will do this at an angle.
The controls I have working now work like this, A and D move you forwards and backwards and W and S move closer and further from the camera. I have my code working sort of but , whenever the player turns around and then tries to strafe shoot, the player will begin shooting at an angle instead of straight on.
If you tap the A or the D key in the direction you are facing the player will correct itself but I want to have to avoid having to do this. Here is the code(Java Script) that I am working with. It’s a collection of code from here that I have found on the net. So please let me know if I am doing something wrong.
var moveSpeed : float = 6.0;
var jumpSpeed : float = 8.0;
var gravity : float = 20.0;
var runSpeed : float = 1.0;
var strafeSpeed : float = 6.0;
var startPosition : Vector3; //For storing the starting position of the player.
private var dead = false;
static var moveDirection : Vector3 = Vector3.zero;
static var strafeDirection : Vector3 = Vector3.zero;
function OnControllerColliderHit(hit : ControllerColliderHit)
{
if (hit.gameObject.tag == "worldKill")
{
dead = true;
HealthController.LIVES -= 1;
//This is a Debug to make sure health is working.
//HealthController.HEALTH -= 50;
}
}
function Start()
{
//Get the starting position of the player so that we can respawn them there if they die.
startPosition = transform.position;
}
function Update()
{
var controller : CharacterController = GetComponent(CharacterController);
if(controller.isGrounded)
{
strafeDirection = Vector3(Input.GetAxis("Horizontal"),0,0);
moveDirection = Vector3(Input.GetAxis("Vertical"),0,Input.GetAxis("Horizontal"));
moveDirection *= moveSpeed;
//This needs much more testing to fully understand
if (strafeDirection.sqrMagnitude > 0.01)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(moveDirection), 1);
}
if(Input.GetButton("Jump"))
{
moveDirection.y = jumpSpeed;
}
}
// Apply Gravity
moveDirection.y -= gravity * Time.deltaTime;
// Move the controller
controller.Move(moveDirection * Time.deltaTime);
}
function LateUpdate()
{
if(dead)
{
//Move the player back to the spawn
transform.position = startPosition;
gameObject.Find("Main Camera").transform.position = Vector3(0,0,0);
dead = false;
}
}
Thanks for the help!!!