Been a while since I posted, but having trouble with a scripting issue, and would love some help/insight if possible.
I am working with the Third Person Lerpz game tutorial which relies on the “Character Controller” to handle movement and call animations. I like the way Lerpz moves, and the options he has, but I am using a different input I purchased in the asset store. This relies on the “Rigidbody” to handle movement. I essentially need to bridge the two so I can control Lerpz with the controls I bought (again, based on rigidbody) but call the movement and animation that is based on the Character Controller.
From what I can tell right now, movement and other activities based on one component do not work well with the other. Am I missing something, or do I need to rewrite the entire interface and scripts all over from the start?
Thanks legend. I definitely know I need to change scripts, I just haven’t been able to figure out how to change them so they work nicely together. Here’s what I’ve figured out so far:
In lerpz, ThirdPersonController.js handles the movement, and calls ThirdPersonPlayerAnimation.js to invoke animations.
In my other controller code I bought Player_PlayerRelative.js handles movement, it seems to be much simpler and cleaner code and the camera reacts much nicer, but they never call animations in it.
So, that’s where I’m having issues. I’m trying to feed the information such as speed and current location etc from Player_PlayerRelative into ThirdPersonController so the animations are called appropriately. I have tried having Player_PlayerRelative call the animations directly, but that doesn’t work since it uses rigidbody instead of character controller. I’ll post the code in the following posts.
Edit: I should mention - I’m not looking for someone to completely solve my issue for me, or debug all of my code, I’m just looking for some direction on how to get started attacking this issue.
var runSpeedScale = 1.0;
var walkSpeedScale = 1.0;
function Start ()
{
// By default loop all animations
animation.wrapMode = WrapMode.Loop;
animation["run"].layer = -1;
animation["walk"].layer = -1;
animation["idle"].layer = -2;
animation.SyncLayer(-1);
animation["ledgefall"].layer = 9;
animation["ledgefall"].wrapMode = WrapMode.Loop;
// The jump animation is clamped and overrides all others
animation["jump"].layer = 10;
animation["jump"].wrapMode = WrapMode.ClampForever;
animation["jumpfall"].layer = 10;
animation["jumpfall"].wrapMode = WrapMode.ClampForever;
// This is the jet-pack controlled descent animation.
animation["jetpackjump"].layer = 10;
animation["jetpackjump"].wrapMode = WrapMode.ClampForever;
animation["jumpland"].layer = 10;
animation["jumpland"].wrapMode = WrapMode.Once;
animation["walljump"].layer = 11;
animation["walljump"].wrapMode = WrapMode.Once;
// we actually use this as a "got hit" animation
animation["buttstomp"].speed = 0.15;
animation["buttstomp"].layer = 20;
animation["buttstomp"].wrapMode = WrapMode.Once;
var punch = animation["punch"];
punch.wrapMode = WrapMode.Once;
// We are in full control here - don't let any other animations play when we start
animation.Stop();
animation.Play("idle");
}
function Update ()
{
var playerController : ThirdPersonController = GetComponent(ThirdPersonController);
//var playerController : Player_PlayerRelative = GetComponent(Player_PlayerRelative);
var currentSpeed = playerController.GetSpeed();
//Debug.Log(currentSpeed);
// Fade in run
if (currentSpeed > playerController.walkSpeed)
{
animation.CrossFade("run");
// We fade out jumpland quick otherwise we get sliding feet
animation.Blend("jumpland", 0);
}
// Fade in walk
else if (currentSpeed > 0.1)
{
animation.CrossFade("walk");
// We fade out jumpland realy quick otherwise we get sliding feet
animation.Blend("jumpland", 0);
}
// Fade out walk and run
else
{
animation.Blend("walk", 0.0, 0.3);
animation.Blend("run", 0.0, 0.3);
animation.Blend("run", 0.0, 0.3);
}
animation["run"].normalizedSpeed = runSpeedScale;
animation["walk"].normalizedSpeed = walkSpeedScale;
if (playerController.IsJumping ())
{
if (playerController.IsControlledDescent())
{
animation.CrossFade ("jetpackjump", 0.2);
}
else if (playerController.HasJumpReachedApex ())
{
animation.CrossFade ("jumpfall", 0.2);
}
else
{
animation.CrossFade ("jump", 0.2);
}
}
// We fell down somewhere
else if (!playerController.IsGroundedWithTimeout())
{
animation.CrossFade ("ledgefall", 0.2);
}
// We are not falling down anymore
else
{
animation.Blend ("ledgefall", 0.0, 0.2);
}
}
function DidLand () {
animation.Play("jumpland");
}
function DidButtStomp () {
animation.CrossFade("buttstomp", 0.1);
animation.CrossFadeQueued("jumpland", 0.2);
}
function Slam () {
animation.CrossFade("buttstomp", 0.2);
var playerController : ThirdPersonController = GetComponent(ThirdPersonController);
while(!playerController.IsGrounded())
{
yield;
}
animation.Blend("buttstomp", 0, 0);
}
function DidWallJump ()
{
// Wall jump animation is played without fade.
// We are turning the character controller 180 degrees around when doing a wall jump so the animation accounts for that.
// But we really have to make sure that the animation is in full control so
// that we don't do weird blends between 180 degree apart rotations
animation.Play ("walljump");
}
@script AddComponentMenu ("Third Person Player/Third Person Player Animation")
//
// 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 for the character
var gravity = 20.0;
// The gravity in controlled descent mode
var controlledDescentGravity = 2.0;
var speedSmoothing = 10.0;
var rotateSpeed = 500.0;
var trotAfterSeconds = 1.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 lastGroundedTime = 0.0;
private var lean = 0.0;
private var slammed = false;
private var isControllable = true;
function Awake ()
{
moveDirection = transform.TransformDirection(Vector3.forward);
}
// This next function responds to the "HidePlayer" message by hiding the player.
// The message is also 'replied to' by identically-named functions in the collision-handling scripts.
// - Used by the LevelStatus script when the level completed animation is triggered.
function HidePlayer()
{
GameObject.Find("rootJoint").GetComponent(SkinnedMeshRenderer).enabled = false; // stop rendering the player.
isControllable = false; // disable player controls.
}
// This is a complementary function to the above. We don't use it in the tutorial, but it's included for
// the sake of completeness. (I like orthogonal APIs; so sue me!)
function ShowPlayer()
{
GameObject.Find("rootJoint").GetComponent(SkinnedMeshRenderer).enabled = true; // start rendering the player again.
isControllable = true; // allow player to control the character again.
}
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 (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;
}
// In air controls
else
{
// Lock camera while in air
if (jumping)
lockCameraTimer = 0.0;
if (isMoving)
inAirVelocity += targetDirection.normalized * Time.deltaTime * inAirControlAcceleration;
}
}
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);
}
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);
}
}
}
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;
}
}
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);
}
function DidJump ()
{
jumping = true;
jumpingReachedApex = false;
lastJumpTime = Time.time;
lastJumpStartHeight = transform.position.y;
touchWallJumpTime = -1;
lastJumpButtonTime = -10;
}
function Update() {
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
var controller : CharacterController = GetComponent(CharacterController);
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)
{
// changed this
//var xzMove = movement;
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);
}
}
}
function OnControllerColliderHit (hit : ControllerColliderHit )
{
// Debug.DrawRay(hit.point, hit.normal);
if (hit.moveDirection.y > 0.01)
return;
wallJumpContactNormal = hit.normal;
}
function GetSpeed () {
return moveSpeed;
}
function IsJumping () {
return jumping !slammed;
}
function IsGrounded () {
return (collisionFlags CollisionFlags.CollidedBelow) != 0;
}
function SuperJump (height : float)
{
verticalSpeed = CalculateJumpVerticalSpeed (height);
collisionFlags = CollisionFlags.None;
SendMessage("DidJump", SendMessageOptions.DontRequireReceiver);
}
function SuperJump (height : float, jumpVelocity : Vector3)
{
verticalSpeed = CalculateJumpVerticalSpeed (height);
inAirVelocity = jumpVelocity;
collisionFlags = CollisionFlags.None;
SendMessage("DidJump", SendMessageOptions.DontRequireReceiver);
}
function Slam (direction : Vector3)
{
verticalSpeed = CalculateJumpVerticalSpeed (1);
inAirVelocity = direction * 6;
direction.y = 0.6;
Quaternion.LookRotation(-direction);
var controller : CharacterController = GetComponent(CharacterController);
controller.height = 0.5;
slammed = true;
collisionFlags = CollisionFlags.None;
SendMessage("DidJump", SendMessageOptions.DontRequireReceiver);
}
function GetDirection () {
return moveDirection;
}
function IsMovingBackwards () {
return movingBack;
}
function GetLockCameraTimer ()
{
return lockCameraTimer;
}
function IsMoving () : boolean
{
return Mathf.Abs(Input.GetAxisRaw("Vertical")) + Mathf.Abs(Input.GetAxisRaw("Horizontal")) > 0.5;
}
function HasJumpReachedApex ()
{
return jumpingReachedApex;
}
function IsGroundedWithTimeout ()
{
return lastGroundedTime + groundedTimeout > Time.time;
}
function IsControlledDescent ()
{
// * When falling down we use controlledDescentGravity (only when holding down jump)
var jumpButton = Input.GetButton("Jump");
return canControlDescent verticalSpeed <= 0.0 jumpButton jumping;
}
function Reset ()
{
gameObject.tag = "Player";
}
// Require a character controller to be attached to the same game object
@script RequireComponent(CharacterController)
@script AddComponentMenu("Third Person Player/Third Person Controller")
var walkSpeed : float; //Force applied when grounded
var runSpeed = 26.0;
var airSpeed : float; //Force applied when in air
var jumpSpeed : float; //Force applied when jumping
var touchHorizontalRotationSpeed : float; //Horizontal rotation speed of the player when using touch-joystick
var mouseHorizontalRotationSpeed : float; //Horizontal rotation speed of the player when using the mouse
var onGroundDrag : float; //Rigidbody drag used on ground
var inAirDrag : float; //Rigidbody drag used in air
var keyboardMouseEnabled : boolean; //Is keyboard and mouse used for moving and rotating the player, useful for Editor testing
var movementJoystick : Joystick; //Joystick that controls the player movement
var rotationJoystick : Joystick; //Joystick that controls the camera pivot rotation
private var onGround : boolean = false; //Determines whether the player is grounded or in air
private var jump : boolean = false; //Determines whether the player should jump
private var rb : Rigidbody; //Reference to the rigidbody component of the game object
private var t : Transform; //Reference to the transform component of the game object
var canControlDescent = true;
// The current vertical speed
private var verticalSpeed = 0.0;
private var moveSpeed = 0.0;
// Are we jumping? (Initiated with jump button and not grounded yet)
private var jumping = false;
private var jumpingReachedApex = false;
private var groundedTimeout = 0.25;
private var lastGroundedTime = 0.0;
private var slammed = false;
function Awake() {
rb = rigidbody; //Cache rigidbody component
t = transform; //Cache transform component
gameObject.layer = 8; //Set gameObject layer to Player layer
}
//Check for one-off input in the Update loop since checking for input in FixedUpdate can lead to lost input events
function Update() {
//Since we're not applying rotation as torque, we don't need to do it in FixedUpdate
if(rotationJoystick) { //If rotation joystick exists
rb.MoveRotation(rb.rotation * Quaternion.Euler(Vector3.up * rotationJoystick.GetAxis().x * touchHorizontalRotationSpeed * Time.deltaTime)); //Rotate player using rotation joystick axis
}
if(keyboardMouseEnabled) { //If keyboard and mouse are enabled
rb.MoveRotation(rb.rotation * Quaternion.Euler(Vector3.up * Input.GetAxis("Mouse X") * mouseHorizontalRotationSpeed * Time.deltaTime)); //Rotate player using mouse axis
}
if(Input.GetKeyDown(KeyCode.Space) keyboardMouseEnabled) { //If Space is hit and keyboard is enabled
Jump();
}
}
//Apply physics forces in FixedUpdate
function FixedUpdate() {
//Add force in the direction of movement
var movement : Vector3;
if(movementJoystick) { //If movement joystick exists
movement = movementJoystick.GetAxis(); //Get movement joystick axis
if(movement.x != 0)
moveSpeed = runSpeed;
else
moveSpeed = walkSpeed;
lastGroundedTime = Time.time;
//Add force to player rigidbody using movement joystick axis
rb.AddRelativeForce(movement.y * Vector3.forward * ((onGround) ? runSpeed : airSpeed));
rb.AddRelativeForce(movement.x * Vector3.right * ((onGround) ? runSpeed : airSpeed));
}
if(keyboardMouseEnabled) { //If keyboard and mouse are enabled
movement = Vector3(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"), 0); //Get keyboard movement axis
if(movement.sqrMagnitude > 1)
movement.Normalize();
if(movement.x != 0 || movement.y != 0)
moveSpeed = runSpeed;
else
moveSpeed = walkSpeed;
//Add force to player rigidbody using keyboard axis
Debug.Log(moveSpeed);
lastGroundedTime = Time.time;
rb.AddRelativeForce(movement.y * Vector3.forward * ((onGround) ? runSpeed : airSpeed));
rb.AddRelativeForce(movement.x * Vector3.right * ((onGround) ? runSpeed : airSpeed));
}
if(jump) {
rb.AddForce(t.up * jumpSpeed); //Add upwards force to make player jump
onGround = false; //Player is no longer grounded
jumpingReachedApex = true;
jumping = true;
jump = false;
rb.drag = inAirDrag; //Change rigidbody drag to allow for better movement in air
SendMessage("DidLand", SendMessageOptions.DontRequireReceiver);
}
}
//If player is on ground, sets jump to true so player will jump when next FixedUpdate is called
function Jump() {
if(onGround){
jump = true;
jumping = false;
}
else
jumping = true;
}
//Check for collisions to determine when the player is on the ground
function OnCollisionEnter(collision : Collision) {
var collisionAngle = Vector3.Angle(collision.contacts[0].normal, Vector3.up); //Calculate angle between the up vector and the collision contact's normal
if(collisionAngle < 40.0) { //If the angle difference is small enough, accept collision as hitting the ground
onGround = true; //Player is grounded
rb.drag = onGroundDrag; //Restore original drag value
}
}
function OnCollisionStay(collision : Collision) {
var collisionAngle = Vector3.Angle(collision.contacts[0].normal, Vector3.up); //Calculate angle between the up vector and the collision contact's normal
if(collisionAngle < 40.0) { //If the angle difference is small enough, accept collision as hitting the ground
onGround = true; //Player is grounded
rb.drag = onGroundDrag; //Restore original drag value
}
}
function OnCollisionExit (collision : Collision) {
onGround = false;
rb.drag = inAirDrag;
}
function GetSpeed () {
return moveSpeed;
}
function IsJumping () {
return jumping !slammed;
}
function HasJumpReachedApex ()
{
return jumpingReachedApex;
}
function IsControlledDescent ()
{
// * When falling down we use controlledDescentGravity (only when holding down jump)
var jumpButton = Input.GetButton("Jump");
return canControlDescent verticalSpeed <= 0.0 jumpButton jumping;
}
function IsGroundedWithTimeout ()
{
return lastGroundedTime + groundedTimeout > Time.time;
}