- Home /
Javascript controller conflict issue
Edit: I found the source of all three issues, which was this one line:
transform.rotation = Quaternion.LookRotation(moveDirection);
Removing that got rid of the camera jerking problems, allows me to look around with the mouse, and allows me to walk backward. However, when I removed it I lost the ability to turn the character with the A, D, and left/right arrow keys and can now only strafe with them. If anyone could tell me how to get that rotation movement input ability back without causing the former problems I'd appreciate it. Thanks!
Original Post:
I'm new to javascript and I'm having a bit of difficulty. I'm trying to take the code from the Animated Soldier example scene and give it the ability to jump (while also having directional control during the jump.) I've taken code from the standard asset third person controller movement script and attempted to combine it with the animated soldier soldiermovement script to give it this ability, but I'm having controller conflict issues.
In the example scene both the mouse and keyboard control movement. The soldier can walk backwards and also fires a weapon with left mouse click. In my combination of the two scripts I've been able to get the soldier to both jump and fire the weapon while jumping. While he's in the air the controls work perfectly. I can look around using the mouse, fire the weapon, and control movement in any direction including backward.
When he's grounded though things get glitchy. The camera jerks all over the place when he goes from standing still to moving left or right. Backward walking doesn't work. Mouse control of the camera doesn't work.
I'm in hopes someone can point me in the right direction so I can get the controls working correctly when he's grounded.
Here's the javascript I've got, any help would be greatly appreciated:
//BEGIN ORIGINAL SOLDIERMOVEMENT!!!
//This script controls how the soldier will move.
@script RequireComponent(CharacterController);
var forwardSpeedMultiplier : float = 3.0;
var strafeSpeedMultiplier : float = 2.0;
var turnSpeedMultiplier : float = 6.0;
var gravity : float = 9.8;
//var soldierLocation : String = "smoothWorldPosition/soldierSkeleton";
var soldier : Transform;
var turnSpeed : float = 0.0;
var forwardSpeed : float = 0.0; //Speed the character will moved at.
var strafeSpeed : float = 0.0;
var isGrounded : boolean;
//END ORIGINAL SOLDIERMOVEMENT!!!
//BEGIN TOOK FROM THIRD PERSON MOVEMENT!!!
// The speed when walking
var walkSpeed = 3.0;
// after trotAfterSeconds of walking we trot with trotSpeed
var trotSpeed = 4.0;
// when pressing "Fire3" button (cmd) we start running
var runSpeed = 6.0;
var inAirControlAcceleration = 3.0;
// How high do we jump when pressing jump and letting go immediately
var jumpHeight = 0.5;
// We add extraJumpHeight meters on top when holding the button down longer while jumping
var extraJumpHeight = 2.5;
// The gravity in controlled descent mode
var controlledDescentGravity = 2.0;
var speedSmoothing = 10.0;
var rotateSpeed = 500.0;
var trotAfterSeconds = 3.0;
var canJump = true;
var canControlDescent = true;
var canWallJump = false;
private var jumpRepeatTime = 0.05;
private var wallJumpTimeout = 0.15;
private var jumpTimeout = 0.15;
private var groundedTimeout = 0.25;
// The camera doesnt start following the target immediately but waits for a split second to avoid too much waving around.
private var lockCameraTimer = 0.0;
// The current move direction in x-z
private var moveDirection = Vector3.zero;
// The current vertical speed
private var verticalSpeed = 0.0;
// The current x-z move speed
private var moveSpeed = 0.0;
// The last collision flags returned from controller.Move
private var collisionFlags : CollisionFlags;
// Are we jumping? (Initiated with jump button and not grounded yet)
private var jumping = false;
private var jumpingReachedApex = false;
// Are we moving backwards (This locks the camera to not do a 180 degree spin)
private var movingBack = false;
// Is the user pressing any keys?
private var isMoving = false;
// When did the user start walking (Used for going into trot after a while)
private var walkTimeStart = 0.0;
// Last time the jump button was clicked down
private var lastJumpButtonTime = -10.0;
// Last time we performed a jump
private var lastJumpTime = -1.0;
// Average normal of the last touched geometry
private var wallJumpContactNormal : Vector3;
private var wallJumpContactNormalHeight : float;
// the height we jumped from (Used to determine for how long to apply extra jump power after jumping.)
private var lastJumpStartHeight = 0.0;
// When did we touch the wall the first time during this jump (Used for wall jumping)
private var touchWallJumpTime = -1.0;
private var inAirVelocity = Vector3.zero;
private var lean = 0.0;
private var slammed = false;
private var isControllable = true;
//END TOOK FROM THIRD PERSON MOVEMENT!!!
//BEGIN ORIGINAL SOLDIERMOVEMENT!!!
private var stopAfterLanding : float = 0.0; //How much time in seconds will the character stop after landing.
private var fallSpeed : float = 0.0;
private var lastGroundedTime : float; //Last time since soldier was touching the ground.
private var lastLandingTime : float; //Last time since the soldier landed after a fall.
private var targetForwardSpeed : float;
private var targetStrafeSpeed : float;
private var crouchControllerScript : crouchController;
private var isFalling : boolean;
private var healthScript : health;
private var recoilAmount : float;
private var recoilAmountTarget : float;
//END ORIGINAL SOLDIERMOVEMENT!!!
//BEGIN TOOK FROM THIRD PERSON MOVEMENT!!!
//Begin function Awake
function Awake ()
{
moveDirection = transform.TransformDirection(Vector3.forward);
}
//End function Awake
//END TOOK FROM THIRD PERSON MOVEMENT!!!
//BEGIN ORIGINAL SOLDIERMOVEMENT!!!
//Begin function Start
function Start()
{
crouchControllerScript = GetComponent("crouchController");
healthScript = GetComponent("health");
isFalling = false;
//soldier = transform.Find(soldierLocation);
}
//End function Start
//END ORIGINAL SOLDIERMOVEMENT!!!
//BEGIN TOOK FROM THIRD PERSON MOVEMENT!!!
//Begin function UpdateSmoothedMovementDirection
function UpdateSmoothedMovementDirection ()
{
var cameraTransform = Camera.main.transform;
var grounded = IsGrounded();
// Forward vector relative to the camera along the x-z plane
var forward = cameraTransform.TransformDirection(Vector3.forward);
forward.y = 0;
forward = forward.normalized;
// Right vector relative to the camera
// Always orthogonal to the forward vector
var right = Vector3(forward.z, 0, -forward.x);
var v = Input.GetAxisRaw("Vertical");
var h = Input.GetAxisRaw("Horizontal");
// Are we moving backwards or looking backwards
if (v < -0.2)
movingBack = true;
else
movingBack = false;
var wasMoving = isMoving;
isMoving = Mathf.Abs (h) > 0.1 || Mathf.Abs (v) > 0.1;
// Target direction relative to the camera
var targetDirection = h * right + v * forward;
// Grounded controls
// If character is grounded this is its movement behavior
if (grounded)
{
// Lock camera for short period when transitioning moving & standing still
//!!!!! lockCameraTimer += Time.deltaTime;
//!!!!! if (isMoving != wasMoving)
//!!!!! lockCameraTimer = 0.0;
// We store speed and direction seperately,
// so that when the character stands still we still have a valid forward direction
// moveDirection is always normalized, and we only update it if there is user input.
if (targetDirection != Vector3.zero)
{
// If we are really slow, just snap to the target direction
if (moveSpeed < walkSpeed * 0.9 && grounded)
{
moveDirection = targetDirection.normalized;
}
// Otherwise smoothly turn towards it
else
{
moveDirection = Vector3.RotateTowards(moveDirection, targetDirection, rotateSpeed * Mathf.Deg2Rad * Time.deltaTime, 1000);
moveDirection = moveDirection.normalized;
}
}
// Smooth the speed based on the current target direction
var curSmooth = speedSmoothing * Time.deltaTime;
// Choose target speed
//* We want to support analog input but make sure you cant walk faster diagonally than just forward or sideways
var targetSpeed = Mathf.Min(targetDirection.magnitude, 1.0);
// Pick speed modifier
if (Input.GetButton ("Fire3"))
{
targetSpeed *= runSpeed;
}
else if (Time.time - trotAfterSeconds > walkTimeStart)
{
targetSpeed *= trotSpeed;
}
else
{
targetSpeed *= walkSpeed;
}
moveSpeed = Mathf.Lerp(moveSpeed, targetSpeed, curSmooth);
// Reset walk time start when we slow down
if (moveSpeed < walkSpeed * 0.3)
walkTimeStart = Time.time;
}
// End If character is grounded this is its movement behavior
// In air controls
// If character is NOT grounded this is its movement behavior
else
{
// Lock camera while in air
//!!!!! if (jumping)
//!!!!! lockCameraTimer = 0.0;
if (isMoving)
inAirVelocity += targetDirection.normalized * Time.deltaTime * inAirControlAcceleration;
}
// End If character is grounded this is its movement behavior
}
//End function UpdateSmoothedMovementDirection
//END TOOK FROM THIRD PERSON MOVEMENT!!!
//BEGIN ORIGINAL SOLDIERMOVEMENT!!!
//Begin function Update
function Update ()
{
var controller : CharacterController = GetComponent(CharacterController);
//Hit recoil.
var recoilVector : Vector3 = Vector3.zero;
var recoilInhibit : float = 1.0;
var deathInhibit : float = 1.0;
if (healthScript != null){
var lastHitTime : float = healthScript.GetLastHitTime();
var recoilDirecion : Vector3 = healthScript.GetrecoilDirecion();
var maxRecoil : float = 0.6;
var timeAfterHit : float = Time.time - lastHitTime;
var recoilAmountTarget : float = 0.0;
if(timeAfterHit < maxRecoil && lastHitTime != 0){
recoilAmountTarget = maxRecoil-timeAfterHit;
recoilAmountTarget *= (1-Mathf.Abs(Input.GetAxis("Vertical")));
recoilAmountTarget *= (1-Mathf.Abs(Input.GetAxis("Horizontal")));
}
if(recoilAmount < recoilAmountTarget){
recoilAmount = Mathf.Lerp(recoilAmount, recoilAmountTarget, Time.deltaTime);
}
else{
recoilAmount = Mathf.Lerp(recoilAmount, recoilAmountTarget, Time.deltaTime*20);
}
var biasRecoilAmount : float = recoilAmount; //Bias to 0.
biasRecoilAmount /= maxRecoil;
biasRecoilAmount = Mathf.Pow(biasRecoilAmount,2.0);
biasRecoilAmount *= maxRecoil;
recoilVector = recoilDirecion * biasRecoilAmount;
recoilInhibit = 1 -(recoilAmount*0.65/maxRecoil);
var health : float = healthScript.health;
if(health <= 0){
deathInhibit = 0;
}
else{
deathInhibit = 1.0;
}
}
//Position. !!!!!NEEDED FOR JUMP TO WORK!!!!!
if (isGrounded){
if (isFalling){
isFalling = false;
lastLandingTime = Time.time;
stopAfterLanding = (lastLandingTime - lastGroundedTime) * 2.0;
}
fallSpeed = 0.0;
}
else{
if (!isFalling){
isFalling = true;
lastGroundedTime = Time.time;
}
fallSpeed += gravity * Time.deltaTime;
}
var moveDirection1 : Vector3;
moveDirection1.y -= fallSpeed;
if (isGrounded){
targetForwardSpeed = Input.GetAxis("Vertical");
targetStrafeSpeed = Input.GetAxis("Horizontal");
targetForwardSpeed *= forwardSpeedMultiplier;
targetStrafeSpeed *= strafeSpeedMultiplier;
if(Input.GetAxis("Vertical") < 0){//Slow down going backwards;
targetForwardSpeed *= 0.5;
}
if(Input.GetKey(KeyCode.LeftShift)){//Sprint with left shift;
targetForwardSpeed *= 1.5;
targetStrafeSpeed *= 1.5;
}
}
if(crouchControllerScript != null){ //Crouch speed multiplier.
targetForwardSpeed = Mathf.Lerp(targetForwardSpeed, targetForwardSpeed * crouchControllerScript.crouchSpeedMultiplier, crouchControllerScript.globalCrouchBlend);
}
if(Time.time <= lastLandingTime + stopAfterLanding && stopAfterLanding > 0.5){
var timeSinceLanding : float = Time.time - lastLandingTime;
var landingSpeedInhibit : float = Mathf.Pow(timeSinceLanding / stopAfterLanding, 1.5);
targetForwardSpeed *= landingSpeedInhibit;
targetStrafeSpeed *= landingSpeedInhibit;
}
forwardSpeed = Mathf.Lerp(forwardSpeed, targetForwardSpeed, Time.deltaTime * 15.0);
strafeSpeed = Mathf.Lerp(strafeSpeed, targetStrafeSpeed, Time.deltaTime * 15.0);
moveDirection1 += soldier.forward * forwardSpeed * recoilInhibit * deathInhibit;
moveDirection1 += soldier.right * strafeSpeed * recoilInhibit * deathInhibit;
moveDirection1 += recoilVector;
//!!!!! controller.Move(moveDirection1 * Time.deltaTime);//Move the controller. !!!!!! DISABLES ABILITY TO JUMP !!!!!
//End Position. !!!!! END NEEDED FOR JUMP TO WORK !!!!!
//Rotation. !!!!! ALSO NEEDED FOR JUMP TO WORK!!!!!
var targetTurnSpeed : float = 0.0;
targetTurnSpeed= Input.GetAxis("Mouse X");
targetTurnSpeed *= Mathf.Pow(turnSpeedMultiplier,3);
targetTurnSpeed *= deathInhibit;
turnSpeed = Mathf.Lerp(turnSpeed, targetTurnSpeed, Time.deltaTime * 25.0);
transform.rotation.eulerAngles.y += turnSpeed * Time.deltaTime;
//End Rotation. !!!!! END ALSO NEEDED FOR JUMP TO WORK!!!!!
//END ORIGINAL SOLDIERMOVEMENT!!!
//BEGIN TOOK FROM THIRD PERSON MOVEMENT!!!
if (!isControllable)
{
// kill all inputs if not controllable.
Input.ResetInputAxes();
}
if (Input.GetButtonDown ("Jump"))
{
lastJumpButtonTime = Time.time;
}
UpdateSmoothedMovementDirection();
// Apply gravity
// - extra power jump modifies gravity
// - controlledDescent mode modifies gravity
ApplyGravity ();
// Perform a wall jump logic
// - Make sure we are jumping against wall etc.
// - Then apply jump in the right direction)
if (canWallJump)
ApplyWallJump();
// Apply jumping logic
ApplyJumping ();
// Calculate actual motion
var movement = moveDirection * moveSpeed + Vector3 (0, verticalSpeed, 0) + inAirVelocity;
movement *= Time.deltaTime;
// Move the controller
wallJumpContactNormal = Vector3.zero;
collisionFlags = controller.Move(movement);
// Set rotation to the move direction
if (IsGrounded())
{
if(slammed) // we got knocked over by an enemy. We need to reset some stuff
{
slammed = false;
controller.height = 2;
transform.position.y += 0.75;
}
transform.rotation = Quaternion.LookRotation(moveDirection);
}
else
{
if(!slammed)
{
var xzMove = movement;
xzMove.y = 0;
if (xzMove.sqrMagnitude > 0.001)
{
transform.rotation = Quaternion.LookRotation(xzMove);
}
}
}
// We are in jump mode but just became grounded
if (IsGrounded())
{
lastGroundedTime = Time.time;
inAirVelocity = Vector3.zero;
if (jumping)
{
jumping = false;
SendMessage("DidLand", SendMessageOptions.DontRequireReceiver);
}
}
}
//End function Update
//Begin function ApplyWallJump
function ApplyWallJump ()
{
// We must actually jump against a wall for this to work
if (!jumping)
return;
// Store when we first touched a wall during this jump
if (collisionFlags == CollisionFlags.CollidedSides)
{
touchWallJumpTime = Time.time;
}
// The user can trigger a wall jump by hitting the button shortly before or shortly after hitting the wall the first time.
var mayJump = lastJumpButtonTime > touchWallJumpTime - wallJumpTimeout && lastJumpButtonTime < touchWallJumpTime + wallJumpTimeout;
if (!mayJump)
return;
// Prevent jumping too fast after each other
if (lastJumpTime + jumpRepeatTime > Time.time)
return;
if (Mathf.Abs(wallJumpContactNormal.y) < 0.2)
{
wallJumpContactNormal.y = 0;
moveDirection = wallJumpContactNormal.normalized;
// Wall jump gives us at least trotspeed
moveSpeed = Mathf.Clamp(moveSpeed * 1.5, trotSpeed, runSpeed);
}
else
{
moveSpeed = 0;
}
verticalSpeed = CalculateJumpVerticalSpeed (jumpHeight);
DidJump();
SendMessage("DidWallJump", null, SendMessageOptions.DontRequireReceiver);
}
//End function ApplyWallJump
//Begin function ApplyJumping
function ApplyJumping ()
{
// Prevent jumping too fast after each other
if (lastJumpTime + jumpRepeatTime > Time.time)
return;
if (IsGrounded()) {
// Jump
// - Only when pressing the button down
// - With a timeout so you can press the button slightly before landing
if (canJump && Time.time < lastJumpButtonTime + jumpTimeout) {
verticalSpeed = CalculateJumpVerticalSpeed (jumpHeight);
SendMessage("DidJump", SendMessageOptions.DontRequireReceiver);
}
}
}
//End function ApplyJumping
//Begin function ApplyGravity
function ApplyGravity ()
{
if (isControllable) // don't move player at all if not controllable.
{
// Apply gravity
var jumpButton = Input.GetButton("Jump");
// * When falling down we use controlledDescentGravity (only when holding down jump)
var controlledDescent = canControlDescent && verticalSpeed <= 0.0 && jumpButton && jumping;
// When we reach the apex of the jump we send out a message
if (jumping && !jumpingReachedApex && verticalSpeed <= 0.0)
{
jumpingReachedApex = true;
SendMessage("DidJumpReachApex", SendMessageOptions.DontRequireReceiver);
}
// * When jumping up we don't apply gravity for some time when the user is holding the jump button
// This gives more control over jump height by pressing the button longer
var extraPowerJump = IsJumping () && verticalSpeed > 0.0 && jumpButton && transform.position.y < lastJumpStartHeight + extraJumpHeight;
if (controlledDescent)
verticalSpeed -= controlledDescentGravity * Time.deltaTime;
else if (extraPowerJump)
return;
else if (IsGrounded ())
verticalSpeed = 0.0;
else
verticalSpeed -= gravity * Time.deltaTime;
}
}
//End function ApplyGravity
//Begin function CalculateJumpVerticalSpeed
function CalculateJumpVerticalSpeed (targetJumpHeight : float)
{
// From the jump height and gravity we deduce the upwards speed
// for the character to reach at the apex.
return Mathf.Sqrt(2 * targetJumpHeight * gravity);
}
//End function CalculateJumpVerticalSpeed
//Begin function DidJump
function DidJump ()
{
jumping = true;
jumpingReachedApex = false;
lastJumpTime = Time.time;
lastJumpStartHeight = transform.position.y;
touchWallJumpTime = -1;
lastJumpButtonTime = -10;
}
//End function DidJump
//Begin function IsJumping
//What is the purpose of !slammed variable? It's always set to false and nothing seems to need it. Commented it out.
function IsJumping ()
{
return jumping; //&& !slammed;
}
//End function IsJumping
//Begin function IsGrounded
function IsGrounded ()
{
return (collisionFlags & CollisionFlags.CollidedBelow) != 0;
}
//End function IsGrounded
//END TOOK FROM THIRD PERSON MOVEMENT!!!
Your answer
Follow this Question
Related Questions
Adding Strafing to 3rd Person Controller 2 Answers
Unity Controller Support Help 0 Answers
MMD How to export model and animations to Unity as 3rd person controller? 2 Answers
IsTrigger problem 1 Answer