Unity AI character controller gravity - c#

I am trying to add gravity to my "residents" of a town builder game. Basically the residents just walk around to a random location, wait 2 seconds then do it again. I am trying to add gravity to them so they don't float.
controller = GetComponent<CharacterController>();
moveDirection = Vector3.zero;
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
These four lines are the gravity lines I tried added and very weird things happen such as the resident teleporting up if it touches anything, even the ground. What can I do? I basically just want the residents not to float above the ground and follow the slopes of the land like regular walking.
Below is the whole code if its needed to help solve my problem.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Resident : MonoBehaviour
{
private Vector3 location;
private Quaternion rotation;
private int speed;
private Vector3 moveDirection = Vector3.zero;
private bool canRotate = true;
Vector3 moveVector;
CharacterController controller;
// Start is called before the first frame update
void Start()
{
transform.rotation *= Quaternion.Euler(-90, 0, 0);
controller = GetComponent<CharacterController>();
speed = 5;
SetRandomPos();
StartCoroutine(ExampleCoroutine());
}
void Update()
{
int gravity = 20;
moveDirection = Vector3.zero;
//Check if cjharacter is grounded
moveDirection.y -= gravity * Time.deltaTime;
// Move the controller
controller.Move(moveDirection * Time.deltaTime);
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, location, step);
if (canRotate)
{
transform.LookAt(location);
transform.rotation *= Quaternion.Euler(-90, 90, 0);
canRotate = false;
}
if (transform.position == location)
{
StartCoroutine(ExampleCoroutine());
}
}
void SetRandomPos()
{
location = new Vector3(Random.Range(transform.position.x - 10f, transform.position.x + 10f), transform.position.y, Random.Range(transform.position.z - 10f, transform.position.z + 10f));
canRotate = true;
}
IEnumerator ExampleCoroutine()
{
//yield on a new YieldInstruction that waits for 5 seconds.
yield return new WaitForSeconds(2);
//After we have waited 5 seconds print the time again.
if (transform.position == location)
{
SetRandomPos();
}
}
}

I am not exactly clear what you intend to do, but saw a few issues with the code and tried to fix them. The snippet is untested, I just added what I believe to be the correction that should fix your issues.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
private Vector3 location;
private Coroutine changeMovement = null;
private float speed;
private Vector3 playerVelocity = Vector3.zero;
CharacterController controller;
// Start is called before the first frame update
void Start()
{
controller = GetComponent<CharacterController>();
speed = 5;
SetRandomPos();
}
void Update()
{
bool groundedPlayer = controller.isGrounded;
if (groundedPlayer && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
Vector3 move = (transform.position - location).normalized;
controller.Move(move * Time.deltaTime * speed);
if (move != Vector3.zero)
{
gameObject.transform.forward = move;
}
// check if we are close to our goal, then change the goal
if (changeMovement == null && Vector3.Distance(transform.position,location) < 0.1f)
{
changeMovement = StartCoroutine(ExampleCoroutine());
}
playerVelocity.y += gravityValue * Time.deltaTime;
controller.Move(playerVelocity * Time.deltaTime);
}
void SetRandomPos()
{
location = new Vector3(Random.Range(transform.position.x - 10f, transform.position.x + 10f), transform.position.y, Random.Range(transform.position.z - 10f, transform.position.z + 10f));
}
IEnumerator ExampleCoroutine()
{
//yield on a new YieldInstruction that waits for 5 seconds.
yield return new WaitForSeconds(2);
SetRandomPos();
changeMovement = null;
}
Edit: I changed the code and used the CharacterController.Move as a base.

Related

Stop my first person character controller going through the wall in Unity using C#?

As seen in the video here: https://i.gyazo.com/ad45ef9e231fd2f9ec6d4cf76889aece.mp4
My code:
MouseLook.cs:
using UnityEngine;
using System.Collections;
public class MouseLook : MonoBehaviour
{
public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityX = 3F;
public float sensitivityY = 3F;
public Camera playerCamera;
public float minimumX = -360F;
public float maximumX = 360F;
public float minimumY = -60F;
public float maximumY = 60F;
private float rotationX = 0F;
private float rotationY = 0F;
private Quaternion originalRotation;
void Update()
{
if (axes == RotationAxes.MouseXAndY)
{
rotationX += Input.GetAxis("Mouse X") * sensitivityX;
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationX = ClampAngle(rotationX, minimumX, maximumX);
rotationY = ClampAngle(rotationY, minimumY, maximumY);
Quaternion xQuaternion = Quaternion.AngleAxis(rotationX, Vector3.up);
Quaternion yQuaternion = Quaternion.AngleAxis(rotationY, -Vector3.right);
transform.localRotation = originalRotation * xQuaternion * yQuaternion;
}
if (axes == RotationAxes.MouseX)
{
rotationX += Input.GetAxis("Mouse X") * sensitivityX;
rotationX = ClampAngle(rotationX, minimumX, maximumX);
Quaternion xQuaternion = Quaternion.AngleAxis(rotationX, Vector3.up);
transform.localRotation = originalRotation * xQuaternion;
}
if (axes == RotationAxes.MouseY || playerCamera != null)
{
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationY = ClampAngle(rotationY, minimumY, maximumY);
Quaternion yQuaternion = Quaternion.AngleAxis(-rotationY, Vector3.right);
if (playerCamera != null)
{
playerCamera.transform.localRotation = originalRotation * yQuaternion;
}
else
{
transform.localRotation = originalRotation * yQuaternion;
}
}
}
void Start()
{
/*
if (gameObject.GetComponent<Rigidbody>())
{
gameObject.GetComponent<Rigidbody>().freezeRotation = true;
}
*/
originalRotation = transform.localRotation;
}
public static float ClampAngle(float angle, float min, float max)
{
if (angle < -360F)
{
angle += 360F;
}
if (angle > 360F)
{
angle -= 360F;
}
return Mathf.Clamp(angle, min, max);
}
}
FirstPersonController.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using Cursor = UnityEngine.Cursor;
public class FirstPersonController : MonoBehaviour
{
private float speed = 5;
private float jumpPower = 4;
Rigidbody rb;
CapsuleCollider col;
public GameObject crossHair;
bool isActive;
float HorizontalInput;
float VerticalInput;
void Start()
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
rb = GetComponent<Rigidbody>();
col = GetComponent<CapsuleCollider>();
crossHair = GameObject.FindWithTag("CrossHair");
}
void Update()
{
HorizontalInput = Input.GetAxisRaw("Horizontal");
VerticalInput = Input.GetAxisRaw("Vertical");
if (Input.GetKeyDown("escape"))
{
Cursor.lockState = CursorLockMode.None;
}
if (Input.GetButtonDown("Sprint"))
{
speed = 15;
}
if (Input.GetButtonUp("Sprint"))
{
speed = 5;
}
if (Input.GetKeyDown(KeyCode.H))
{
isActive = !isActive;
}
if (isActive)
{
crossHair.SetActive(true);
}
else
{
crossHair.SetActive(false);
}
}
void FixedUpdate()
{
Vector3 xMovement = transform.right * speed * HorizontalInput * Time.deltaTime;
Vector3 zMovement = transform.forward * speed * VerticalInput * Time.deltaTime;
rb.velocity = new Vector3(HorizontalInput, 0, VerticalInput) * speed;
if (isGrounded() && Input.GetButtonDown("Jump"))
{
rb.AddForce(Vector3.up * jumpPower, ForceMode.Impulse);
}
}
private bool isGrounded()
{
return Physics.Raycast(transform.position, Vector3.down, col.bounds.extents.y + 0.1f);
}
}
Is there anything wrong I am doing in this code, if so how do I fix it?
Entire project can be downloaded here: https://github.com/Some-T/FirstPersonController-CSharp
Project has relevant colliders and rigidbodies set up!
Someone has advised me to use shapecast, but I believe that may incorrect? I can't see how that would work as my player does not have character controller component added to it?
Overall how do I stop my first person character controller going through the wall like in the initial video specified above?
Upon further research I have discovered the following:
The answer is to use:
https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html as a quick fix.
But definitively for flawlessness use:
https://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html
As to how in C# I am not so sure, but here is a screen shot I did in bolt asset.
Currently I have movmement working with velocity but it does not work properly, not sure as to why? So overall my question now is how do I get movement working using velocity? I added a line in FirstPersonController.cs that moves the character using velocity of rb.velocity = new Vector3(HorizontalInput, 0, VerticalInput) * speed; so my only question and issue now is my player does not move in the direction the camera on my player is facing so I am not sure how to fix this specific thing overall?
In your project code is different from one that you provided here.
Try to enable rigidbody`s rotation constraint - freeze X and Z rotation, leave only Y. When you rotate your capsule collider (as it works in your project), it can "climb" on a wall.
Do the isGrounded check when you move, and lock movement, if not grounded.
Try to increase Collider.contactOffset
If above does not helps, try to use Rigidbody.velocity instead of Rigidbody.MovePosition.
You can also reduce Rigidbody.drag
In general, pretty good technique is to use NavMesh for movement - in this way, you able to explicitly lock player from movement outside of navmesh surface. But, of course, it doesn`t fit to many gameplays.
Hope, it helps.
upd
You move your player like this:
void FixedUpdate()
{
Vector3 xMovement = transform.right * speed * HorizontalInput * Time.deltaTime;
Vector3 zMovement = transform.forward * speed * VerticalInput * Time.deltaTime;
}
Note, that you not even apply it to rigidbody;
But you get your input this way:
float HorizontalInput = Input.GetAxis("Horizontal");
float VerticalInput = Input.GetAxis("Vertical");
in Update, so input just stays inside Update, and does not applied at all. You declared your variables twice, once on class top, another in Update().

Have enemy accelerate towards player in Unity

I have a script that has the enemy move towards the player at the same speed, but I am trying to make the enemy slow down then accelerate when he is switching directions. The enemy currently just moves left and write towards the player's position.
Here is my code from the script that my boss is attached to in the update function:
Vector2 targetPosition = new Vector2 (player.transform.position.x, transform.position.y);
transform.position = Vector2.MoveTowards (transform.position, targetPosition, moveSpeed * Time.deltaTime);
I have also tried using Lerp and using the transform.position as the first parameter, but the boss goes slower when the player is closer, and faster when the player is faster away.
transform.position = Vector2.Lerp (transform.position, targetPosition, moveSpeed * Time.deltaTime);
Does anyone know how to make the enemy slow down, then gradually increase his speed as he change direction, then return to normal speed after he has finished changing directions
**EDIT: ** full script below
using UnityEngine;
public class Roll : StateMachineBehaviour
{
[SerializeField] private float moveSpeed = 2.4f;
[SerializeField] private float rotateSpeed = 100f;
[SerializeField] private float minRollTime = 6f;
[SerializeField] private float maxRollTime = 8f;
private float rollTimer = 0f;
[SerializeField] private float rightBoundary = 5f;
[SerializeField] private float leftBoundary = -5f;
private Transform playerTransform = null;
private BossHealth bossHealth = null;
private Transform bossTransform = null;
private Transform bodyTransform = null;
private Transform earsTransform = null;
private Vector2 targetPosition = Vector2.zero;
override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
playerTransform = GameObject.FindWithTag("Player").transform;
bossHealth = animator.GetComponent<BossHealth>();
Boss01 boss = FindObjectOfType<Boss01>();
bossTransform = boss.bossTransform;
bodyTransform = boss.bodyTransform;
earsTransform = boss.earsTransform;
rollTimer = Random.Range (minRollTime, maxRollTime);
}
override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
if (bossTransform.position.x >= leftBoundary && bossTransform.position.x <= rightBoundary)
{
targetPosition = new Vector2(playerTransform.position.x, bossTransform.position.y);
bossTransform.position = Vector2.MoveTowards(bossTransform.position, targetPosition, moveSpeed * Time.deltaTime);
if (playerTransform.position.x > 0)
bodyTransform.Rotate(0f, 0f, -rotateSpeed * Time.deltaTime);
else
bodyTransform.Rotate(0f, 0f, rotateSpeed * Time.deltaTime);
}
else if (bossTransform.position.x < leftBoundary)
{
if (playerTransform.position.x > bossTransform.position.x)
{
targetPosition = new Vector2(playerTransform.position.x, bossTransform.position.y);
bossTransform.position = Vector2.MoveTowards(bossTransform.position, targetPosition, moveSpeed * Time.deltaTime);
}
}
else
{
if (playerTransform.position.x < bossTransform.position.x)
{
targetPosition = new Vector2(playerTransform.position.x, bossTransform.position.y);
bossTransform.position = Vector2.MoveTowards(bossTransform.position, targetPosition, moveSpeed * Time.deltaTime);
}
}
if (rollTimer <= 0f)
animator.SetTrigger ("aim");
else
rollTimer -= Time.deltaTime;
if (bossHealth.CheckHealth())
animator.SetTrigger ("transition");
if (earsTransform.rotation != Quaternion.Euler (0f, 0f, 0f))
earsTransform.rotation = Quaternion.Slerp(earsTransform.rotation, Quaternion.Euler(0f, 0f, 0f), 1f * Time.deltaTime);
}
override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
animator.ResetTrigger ("aim");
animator.ResetTrigger ("transition");
}
}
To achieve the position (meters/second) you multiply the speed * Time.deltatime, so you achieve the meters. To handle acceleration, you need to handle variable speed. Acceleration is m/s2, multiplied * Time.deltatime you will have the instant speed, and that speed * Time.deltaTime will give you the position.
Here some pseudocode (step and speed should be class varibles and this modifieed in the update. accel is the constant acceleration, that should be constans for the simplicity's sake, I guess that you need uniformingly accelerated movement):
speed += accel * Time.deltaTime; // instant speed
step = speed * Time.deltaTime; // calculate distance to move
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
With the sign of the accel + or - you will determine if the entities speed is increasing (accelerating) or decreasing (decelerating).
Hope that helps
Edit:
Full script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveTowards : MonoBehaviour
{
public Transform target;
private float step = 0f;
private float speed = 0f;
public float accel = 0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
speed += accel * Time.deltaTime; // instant speed
step = speed * Time.deltaTime; // calculate distance to move
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
}
}
Screenshot of script attached in editor:
Attached the script to the game object you want to move, and attach the transform of the target in the public fielld. The choose your acceleration, positive to accelerate towards an negative to accelerate backwars, and there you got it.

Player's Bumpy Movement

When my player jumps and lands on something it always shakes around like that.
Also, sometimes when I jump a few times in a row (about 10 times) it would go through the ground and just fall down.
I tried using a collider and I don't see anything in the movement script that may cause this. I'm currently using Unity 2018.4.20f1 and Visual Studio c#.
Any solutions?
Player Movement script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public static int movespeed = 6;
public Vector3 userDirection = Vector3.right;
public Rigidbody rb;
public bool isGrounded;
Vector3 jumpMovement;
bool jump = false;
[SerializeField]
float jumpHeight = 1.8f, jumpSpeed = 8f;
void Start()
{
rb = GetComponent<Rigidbody>(); }
void OnCollisionStay()
{
isGrounded = true;
}
public float fallMultiplier = 3.5f;
public float lowJumpMultiplier = 2f;
void Update()
{
//movement
transform.Translate(userDirection * movespeed * Time.deltaTime);
if (Input.GetButton("Jump") && !jump)
StartCoroutine(Jump());
}
IEnumerator Jump()
{
float originalHeight = transform.position.y;
float maxHeight = originalHeight + jumpHeight;
jump = true;
yield return null;
while (transform.position.y < maxHeight)
{
transform.position += transform.up * Time.deltaTime * jumpSpeed;
yield return null;
}
while (transform.position.y > originalHeight)
{
transform.position -= transform.up * Time.deltaTime * jumpSpeed;
yield return null;
}
rb.useGravity = true;
jump = false;
yield return null;
}
}
Edit: I didn't notice the link.
You are forcing it to go down to originalHeight, without checking if there is an object higher than that. You can remove
while (transform.position.y > originalHeight)
{
transform.position -= transform.up * Time.deltaTime * jumpSpeed;
yield return null;
}
and let the rigidbody control gravity (by setting rb.useGravity = true; as you did).
Original answer:
You are probably going below the ground when calling transform.position -= transform.up * Time.deltaTime * jumpSpeed;. Try adding
if (transform.position.y < originalHeight)
transform.position = new Vector3(transform.position.x, originalHeight, transform.position.z)
after it.

How can I add a jump to the player controller?

I want to be able to jump by pressing on space key inside a place like home or space station and also outside.
This is the player controller script attached to a capsule :
It was working fine until I added the jump part. At the top I added this 3 lines :
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
Then in the Update added :
if (controller.isGrounded && Input.GetButton("Jump"))
{
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
But I don't have the variable controller.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 10.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float translation = Input.GetAxis("Vertical") * speed;
float straffe = Input.GetAxis("Horizontal") * speed;
translation *= Time.deltaTime;
straffe *= Time.deltaTime;
transform.Translate(straffe, 0, translation);
if (controller.isGrounded && Input.GetButton("Jump"))
{
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
if (Input.GetKeyDown("escape"))
{
Cursor.lockState = CursorLockMode.Locked;
}
}
}
And this is the cam mouse look script attached to the main camera that is child of the capsule :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CamMouseLook : MonoBehaviour
{
public float sensitivity = 5.0f;
public float smoothing = 2.0f;
Vector2 mouseLook;
Vector2 smoothV;
GameObject character;
// Start is called before the first frame update
void Start()
{
character = this.transform.parent.gameObject;
}
// Update is called once per frame
void Update()
{
var md = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
md = Vector2.Scale(md, new Vector2(sensitivity * smoothing, sensitivity * smoothing));
smoothV.x = Mathf.Lerp(smoothV.x, md.x, 1f / smoothing);
smoothV.y = Mathf.Lerp(smoothV.y, md.y, 1f / smoothing);
mouseLook += smoothV;
mouseLook.y = Mathf.Clamp(mouseLook.y, -90f, 90f);
transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);
character.transform.localRotation = Quaternion.AngleAxis(mouseLook.x, character.transform.up);
}
}
Have you thought about applying a force?
public Rigidbody myphysic;
public float forceofjump = 100f; // or minor or more....
void Awake()
{
myphysic= transform.GetComponent<Rigidbody>();
}
void FixedUpdate()
{
if (controller.isGrounded && Input.GetButton("Jump"))
{
myphysic.AddForce( transform.up * forceofjump, ForceMode.Impulse);
}
}
Vector3.zero is wrong beacouse set all movement vector to zero! so = no actions!
or, exemple:
Vector3 moveDirection = new Vector3(0, 10, 0);
what does it mean:
new Vector3(X=stop, Y=10 of force, Z=stop);

Unity3D Character Continuously Moving Issue

so I'm working on a project in Unity3D and I'm having the following issue:
When I initially start the game, the character is not moving, which is intended. Then, when I hit "W" to move, my character starts moving and animates. However, when I let off the key, she doesn't stop moving forward.
Even if I hit the "S" key to move backward, after I let up, she starts moving forward again while no keys are pressed, and for the life of me I can't figure out why.
Here's the script I'm using on her if that helps:
using UnityEngine;
using System.Collections;
public class PlayerScript : MonoBehaviour
{
private CharacterController controller;
public float speed = 20.0f;
private Vector3 moveDirection = Vector3.zero;
public float gravity = 20.0f;
private bool winState = false;
private bool loseState = false;
private bool isBlocking = false;
private Animator anim;
// Use this for initialization
void Start ()
{
controller = this.GetComponent<CharacterController>();
anim = GetComponent<Animator>();
anim.SetBool("Ready_Bool", true);
}
// Update is called once per frame
void FixedUpdate ()
{
//GameObject center = GameObject.Find("MiddleOfRing");
GameObject opponent = GameObject.Find("Opponent");
checkAnimations();
float turn = Input.GetAxis("Horizontal");
//print("Horizontal: " + turn);
if(turn < 0)
moveLeft();
else if(turn > 0)
moveRight();
float vertDirection = Input.GetAxis("Vertical");
//print ("Vertical: " + vertDirection);
print ("Controller Velocity: " + controller.velocity.magnitude); //for testing
if(controller.isGrounded)
{
moveDirection = transform.forward * vertDirection * speed;
anim.SetFloat("Speed", controller.velocity.magnitude);
}
if(vertDirection > 0)
moveForward(moveDirection);
else if(vertDirection < 0)
moveBackward(moveDirection);
else
controller.Move(moveDirection * Time.deltaTime);
moveDirection.y = moveDirection.y - gravity * Time.deltaTime;
transform.LookAt(opponent.transform.position);
opponent.transform.LookAt(this.transform.position);
}
void moveLeft()
{
GameObject opponent = GameObject.Find("Opponent");
transform.RotateAround(opponent.gameObject.transform.position, Vector3.up, speed/2 * Time.deltaTime);
//for testing purposes, to be replaced with actual AI
opponent.transform.RotateAround(transform.position, Vector3.up, speed/2 * Time.deltaTime);
//tells Animator character is moving left
anim.SetBool("MoveLeft_Bool", true);
anim.SetBool("MoveRight_Bool", false);
anim.SetBool("MoveForward_Bool", false);
anim.SetBool("MoveBackward_Bool", false);
}
void moveRight()
{
GameObject opponent = GameObject.Find("Opponent");
transform.RotateAround(opponent.gameObject.transform.position, Vector3.down, speed/2 * Time.deltaTime);
//for testing purposes, to be replaced with actual AI
opponent.transform.RotateAround(transform.position, Vector3.down, speed/2 * Time.deltaTime);
//tells Animator character is moving right
anim.SetBool("MoveRight_Bool", true);
anim.SetBool("MoveLeft_Bool", false);
anim.SetBool("MoveForward_Bool", false);
anim.SetBool("MoveBackward_Bool", false);
}
void moveForward(Vector3 move)
{
GameObject opponent = GameObject.Find("Opponent");
float distance = Vector3.Distance(this.transform.position, opponent.transform.position);
//keeps characters at a certain distance from each other
if(distance >= 3)
{
controller.Move(move * Time.deltaTime);
}
//tells Animator character is moving forward
anim.SetBool("MoveForward_Bool", true);
anim.SetBool("MoveRight_Bool", false);
anim.SetBool("MoveLeft_Bool", false);
anim.SetBool("MoveBackward_Bool", false);
}
void moveBackward(Vector3 move)
{
GameObject opponent = GameObject.Find("Opponent");
moveDirection = transform.forward * Input.GetAxis("Vertical") * speed;
controller.Move(move * Time.deltaTime);
//tells Animator character is moving backward
anim.SetBool("MoveBackward_Bool", true);
anim.SetBool("MoveRight_Bool", false);
anim.SetBool("MoveForward_Bool", false);
anim.SetBool("MoveLeft_Bool", false);
}
void checkAnimations()
{
AnimatorStateInfo stateInfo = anim.GetCurrentAnimatorStateInfo(0);
if(Input.GetKeyDown(KeyCode.E))
{
anim.SetTrigger("JabR_Trig");
checkHit();
isBlocking = false;
}
else if(Input.GetKeyDown(KeyCode.Q))
{
anim.SetTrigger("JabL_Trig");
checkHit();
isBlocking = false;
}
else if(Input.GetKey(KeyCode.B))
{
anim.SetTrigger("Block_Trig");
isBlocking = true;
}
else
{
isBlocking = false;
}
}
void checkHit()
{
GameObject opponent = GameObject.Find("Opponent");
float distance = Vector3.Distance(this.transform.position, opponent.transform.position);
if(distance <= 4.0f)
{
}
}
public bool getBlocking()
{
return isBlocking;
}
}
I think the problem may be that I'm using controller.velocity.magnitude incorrectly.
If anyone can help me out, I would appreciate it!
this line:
moveDirection = transform.forward * vertDirection * speed;
should be this:
moveDirection = transform.forward * vertDirection * speed * Time.deltaTime;
this else block:
else
controller.Move(moveDirection * Time.deltaTime);
should look like this:
else
controller.Move(Vector3.zero);
I actually figured it out. My animator didn't have one of the transitions set up, so the character was stuck in an animation.
Thanks!

Categories