unity 5 co routine wont exit when told to - c#

I am making a game where the player battles a robot, I have implemented some code to make the AI move back and rotate away from the player if a condition is met. However the co routine that does this loops forever and I am unsure in how to make it break.
void Update ()
{
//looking at player
playerVelocity = ((TTarget.position - previous).magnitude) / Time.deltaTime;
previous = TTarget.position;
GameObject thePlayer = GameObject.Find("Player");
PlayerMovement playerMovement = thePlayer.GetComponent<PlayerMovement>();
enemyHit = playerMovement.hitEnemy;
if (enemyHit == false)
{
//enemy moving
transform.LookAt(TTarget);
transform.Translate(Vector3.forward * Time.deltaTime * movementSpeed);
}
else if (enemyHit == true)
{
StartCoroutine("Evade");
//Debug.Log ("Hello");
StopCoroutine("Evade");
}
}
IEnumerator Evade()
{
//GameObject thePlayer = GameObject.Find("Player");
//PlayerMovement playerMovement = thePlayer.GetComponent<PlayerMovement>();
//enemyHit = playerMovement.hitEnemy;
transform.Translate(Vector3.back * Time.deltaTime * movementSpeed);
yield return new WaitForSeconds(1);
Vector3 to = new Vector3(0, -45, 0);
if (Vector3.Distance(transform.eulerAngles, to) > 0.01f)
{
transform.eulerAngles = Vector3.Lerp(transform.rotation.eulerAngles, to, 99*Time.deltaTime);
}
yield break;
}

Your problem is that you are starting the coroutine, then immediately stopping it.
void Update ()
{
enemyHit = playerMovement.hitEnemy;
if (enemyHit == false)
{
//enemy moving
transform.LookAt(TTarget);
transform.Translate(Vector3.forward * Time.deltaTime * movementSpeed);
}
else if (enemyHit == true)
{
StartCoroutine("Evade");
Debug.Log ("Back From Coroutine");
StopCoroutine("Evade");
Debug.Log("Stopped Coroutine");
}
}
IEnumerator Evade()
{
Debug.Log("Starting Coroutine");
transform.Translate(Vector3.back * Time.deltaTime * movementSpeed);
yield return new WaitForSeconds(1);
Debug.Log("This is never called");
Vector3 to = new Vector3(0, -45, 0);
if (Vector3.Distance(transform.eulerAngles, to) > 0.01f)
{
transform.eulerAngles = Vector3.Lerp(transform.rotation.eulerAngles, to, 99*Time.deltaTime);
}
yield break;
}
This would output:
Starting Coroutine
Back From Coroutine
Stopped Coroutine
I think the better would to do this would just be with a bool and Invoke http://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html
private bool avoidPlayer = false;
void Update ()
{
enemyHit = playerMovement.hitEnemy;
if (enemyHit == false)
{
//enemy moving
transform.LookAt(TTarget);
transform.Translate(Vector3.forward * Time.deltaTime * movementSpeed);
}
else if (enemyHit == true)
{
transform.Translate(Vector3.back * Time.deltaTime * movementSpeed);
avoidPlayer = true;
}
// Invoke the evade function every second until we have avoided the player
if(avoidPlayer)
Invoke("Evade", 1);
}
void Evade()
{
Vector3 to = new Vector3(0, -45, 0);
if (Vector3.Distance(transform.eulerAngles, to) > 0.01f)
transform.eulerAngles = Vector3.Lerp(
transform.rotation.eulerAngles, to, 99*Time.deltaTime);
else
avoidPlayer = false;
}

Related

Getting the right movement down

i want a karlson-esque movement for my game but i cant seem to nail it correctly, i basically want to add a force to the players base velocity just bieng tossed around in the game, like a velocity offset if you will,
for example if the player gets hit by a high velocity cube and tossed back naturally, they should struggle to regain thier stability and kind of come to a gradual halt assuming they are moving in the opposite direction than where they were being tossed, but my method (setting the players velocity) doesnt really work that well for what im trying to achieve, it simply comes to a semi-immediate halt, ive tried interpolation to make a gradual speed increase but input.getaxis and velocity both already somewhat cover that, anything more and the "coming to a halt" part works but movement isnt as snappy as i wish it was, here is my full code (note that i am somewhat of a beginner, ive done coding elsewhere but i just started unity a few weeks ago)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class charactercontroller : MonoBehaviour {
//variables and functions
public float moveSpeed = 7f;
public bool tweening = false;
public bool jumping = false;
public bool reteleporing = false;
public Vector3 smoothedvel;
public Vector3 smoothedvectorweapon;
public float smoothedweaponspeed;
public Vector3 smoothedrotationalvector;
public Quaternion smoothedrotateweapon;
public Vector3 cameraoffset;
public float[] tweeninformation = {3f,5f,6f,7f,8f,9f,10f};
public float[] tweeninformationreverse = {10f,9f,8f,7f,6f,5f,3f};
void Start () {
cameraoffset = new Vector3(0,0,0);
smoothedvel = new Vector3(0,0,0);
smoothedrotateweapon = Quaternion.Euler(0,0,0);
smoothedweaponspeed = 0.1f;
smoothedvectorweapon = new Vector3(0.559f,0,-0.523f);
StartCoroutine(waiter());
}
IEnumerator waiter()
{
while(true)
{
if (new Vector3(Input.GetAxis("Vertical"),0,Input.GetAxis("Horizontal")).magnitude != 0 && Physics.Raycast(transform.position, -Vector3.up, gameObject.GetComponent<Collider>().bounds.extents.y + 0.3f) == true)
{
gameObject.GetComponent<ParticleSystem>().Emit(new ParticleSystem.EmitParams(), 3);
transform.GetChild(0).GetComponent<AudioSource>().pitch = Random.Range(1.0f,1.5f);
transform.GetChild(0).GetComponent<AudioSource>().Play();
}
yield return new WaitForSeconds(0.25f);
}
}
void Update (){
//movement
smoothedrotationalvector = Vector3.Lerp(smoothedrotationalvector, new Vector3(-Input.GetAxis("Vertical"),0,Input.GetAxis("Horizontal")), smoothedweaponspeed);
transform.GetChild(2).GetChild(0).transform.localPosition = Vector3.Lerp(transform.GetChild(2).GetChild(0).transform.localPosition, smoothedvectorweapon, smoothedweaponspeed);
transform.GetChild(2).GetChild(0).transform.localRotation = Quaternion.Lerp(transform.GetChild(2).GetChild(0).transform.localRotation, smoothedrotateweapon, smoothedweaponspeed);
if (new Vector3(Input.GetAxis("Vertical"),0,Input.GetAxis("Horizontal")).magnitude != 0)
{
transform.GetChild(2).transform.LookAt(transform.position + smoothedrotationalvector);
}
if (transform.position.y < -100)
{
reteleporing = true;
}
if (reteleporing == true)
{
transform.position = GameObject.Find("spawnpos").transform.position;
}
if (transform.position.y > 2.4)
{
reteleporing = false;
}
///if (Physics.Raycast(transform.position,transform.forward * Time.deltaTime * Input.GetAxis("Vertical"), gameObject.GetComponent<Collider>().bounds.extents.x + 0.3f) == false && reteleporing == false)
///{
/// transform.Translate(transform.forward * Time.deltaTime * Input.GetAxis("Vertical")* moveSpeed);
///}
///else
///{
// transform.Translate(transform.forward * Time.deltaTime * Input.GetAxis("Vertical")* 1);
//}
//if (Physics.Raycast(transform.position,transform.right * Time.deltaTime * Input.GetAxis("Horizontal"),gameObject.GetComponent<Collider>().bounds.extents.z + 0.3f) == false && reteleporing == false)
//{
// transform.Translate(transform.right * Time.deltaTime * Input.GetAxis("Horizontal")* moveSpeed);
//}
//else
//{
// transform.Translate(transform.right * Time.deltaTime * Input.GetAxis("Horizontal")* 1);
//}
if (reteleporing == false)
{
gameObject.GetComponent<Rigidbody>().velocity = Vector3.Lerp(gameObject.GetComponent<Rigidbody>().velocity,new Vector3(Input.GetAxis("Horizontal") * moveSpeed,gameObject.GetComponent<Rigidbody>().velocity.y,Input.GetAxis("Vertical") * moveSpeed), 0.1f);
}
//if (Physics.Raycast(transform.position, -Vector3.up, gameObject.GetComponent<Collider>().bounds.extents.y + 0.3f) == true)
//{
// gameObject.GetComponent<Rigidbody>().velocity = Vector3.Lerp(gameObject.GetComponent<Rigidbody>().velocity, new Vector3(0,0,0), 0.01f);
//}
//camera controlling
smoothedvel = Vector3.Lerp(smoothedvel, gameObject.GetComponent<Rigidbody>().velocity * 0.1f, 0.1f);
Camera maincam = GameObject. Find("Main Camera"). GetComponent<Camera>();
Vector3 camend = transform.position + new Vector3(Input.GetAxis("Horizontal") * 0.5f,0,0);
maincam.transform.position = transform.position + new Vector3(0, 4, -7f) + cameraoffset;
maincam.transform.LookAt(transform.position + smoothedvel);
//jumping
if (Input.GetKeyDown(KeyCode.Space))
{
if (Physics.Raycast(transform.position, -Vector3.up, gameObject.GetComponent<Collider>().bounds.extents.y + 0.3f) == true)
{
gameObject.GetComponent<Rigidbody>().AddForce(transform.up * 250);
moveSpeed = 9f;
}
}
if (Physics.Raycast(transform.position, -Vector3.up, gameObject.GetComponent<Collider>().bounds.extents.y + 0.3f) == false)
{
moveSpeed = 9f;
jumping = true;
}
else
{
moveSpeed = 7f;
if (jumping == true)
{
jumping = false;
transform.GetChild(1).GetComponent<AudioSource>().Play();
gameObject.GetComponent<ParticleSystem>().Emit(new ParticleSystem.EmitParams(), 4);
StartCoroutine(jumpanimwait());
IEnumerator jumpanimwait()
{
yield return new WaitForSeconds(0.2f);
}
}
}
//weapon
if (Input.GetKeyDown(KeyCode.Mouse0))
{
StartCoroutine(gunwait());
IEnumerator gunwait()
{
smoothedweaponspeed = 0.5f;
smoothedvectorweapon = new Vector3(-0.021f,0.172f,-0.523f);
smoothedrotateweapon = Quaternion.Euler(0,0,33.318f);
transform.GetChild(2).GetChild(0).GetComponent<ParticleSystem>().Emit(new ParticleSystem.EmitParams(), 2);
GameObject clone = Instantiate(GameObject.Find("bullet"), transform.position + transform.GetChild(2).transform.right * 2 + -transform.GetChild(2).transform.forward * 0.5f, Quaternion.Euler(0,0,0), transform.parent);
clone.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.None;
transform.GetChild(2).GetChild(0).GetComponent<AudioSource>().Play();
clone.transform.LookAt(clone.transform.position + transform.GetChild(2).transform.right * 5 + -transform.GetChild(2).transform.forward * 0.5f );
clone.GetComponent<Rigidbody>().velocity = transform.GetChild(2).transform.right * 50;
Destroy(clone, 2);
yield return new WaitForSeconds(0.1f);
smoothedweaponspeed = 0.05f;
smoothedrotateweapon = Quaternion.Euler(0,0,0);
smoothedvectorweapon = new Vector3(0.559f,0,-0.523f);
}
}
}
}
i got it, it was a mixture of programming more movement tech for my controller and generally messing around with physics materials and rigidbody mass, also interpolation was pretty important in the process

Jump script in unity involving rb.velocity not working

Here is my code and inspector data, I am rookie in unity And I do not have an idea why it is not working. I tagged this as a 3D problem, since I think it wouldn't work in either. I watched some youtube videos and other posts, and I cannot find a mistake.I would be grateful for any help.
This is picture of my inspector
public Animator animator;
public SpriteRenderer sprite;
public Rigidbody2D rb;
Vector2 playerDirection;
public float speed;
public float jumpForce;
public float fallMultiplier=2.5f;
public float lowJumpMultiplier=2f;
void Update()
{
playerDirection.x = Input.GetAxisRaw("Horizontal");
//Animation
////////////////////////////////////////////////////
if (playerDirection.x != 0)
animator.SetBool("isMoving", true);
else
animator.SetBool("isMoving", false);
////////////////////////////////////////////////////
//flip
////////////////////////
if (playerDirection.x < 0)
{
sprite.flipX = true;
}
if (playerDirection.x>0)
{
sprite.flipX = false;
}
////////////////////////
//Jump
///////////////////////
////////////////////////
}
private void FixedUpdate()
{
rb.MovePosition(rb.position + speed *playerDirection * Time.fixedDeltaTime);
if (Input.GetButton("Jump"))
{
rb.velocity = Vector2.up * jumpForce;
}
if (rb.velocity.y < 0)
{
rb.velocity += Vector2.up * fallMultiplier * Time.fixedDeltaTime;
}
else
if (rb.velocity.y > 0 && !Input.GetKey(KeyCode.W))
{
rb.velocity += Vector2.up * Physics2D.gravity.y * (lowJumpMultiplier - rb.gravityScale) * Time.fixedDeltaTime;
}
}
First of all you need to understand the difference between Update and FixedUpdate. Update runs at all the frames. FixedUpdate runs at specific time intervals. What you are doing is registering user input in the FixedUpdate. That means that, you need to be lucky and have the FixedUpdate run at the specific frame you pressed the button. If you had pysics calculations, you should indeed place them in the FixedUpdate. However, when jumping, you do not, you simply set the velocity. Now, the falling part is interesting, because you do want that in the FixedUpdate.
Try this:
void Update()
{
playerDirection.x = Input.GetAxisRaw("Horizontal");
//Animation
////////////////////////////////////////////////////
if (playerDirection.x != 0)
animator.SetBool("isMoving", true);
else
animator.SetBool("isMoving", false);
////////////////////////////////////////////////////
//flip
////////////////////////
if (playerDirection.x < 0)
{
sprite.flipX = true;
}
if (playerDirection.x>0)
{
sprite.flipX = false;
}
////////////////////////
//Jump
///////////////////////
if (Input.GetButton("Jump"))
{
Debug.Log("Jumping button registered");
rb.velocity = Vector2.up * jumpForce;
}
////////////////////////
}
private void FixedUpdate()
{
rb.MovePosition(rb.position + speed *playerDirection * Time.fixedDeltaTime);
if (rb.velocity.y < 0)
{
rb.velocity += Vector2.up * fallMultiplier * Time.fixedDeltaTime;
}
else
if (rb.velocity.y > 0 && !Input.GetKey(KeyCode.W))
{
rb.velocity += Vector2.up * Physics2D.gravity.y * (lowJumpMultiplier - rb.gravityScale) * Time.fixedDeltaTime;
}
}
Once you make sure that the jump is registered, it should probably work fine. If however you do NOT get console log when pressing the jump button, you should check your input settings.

Player has little control over the character after dashing in midair

I'm working on a 2.5D player controller right now, and there is a problem with my dash in midair. The dash works, but the character can't be completely controlled on the X axis after the dash is finished until they hit the ground. I want the player to have full control on the X axis right after the dash so that they can dodge appropriately.
void Update()
{
PlayerInput();
}
void FixedUpdate()
{
xMovement();
yMovement();
}
void PlayerInput()
{
//Registers X and Y movement
horizontalInput = Input.GetAxis("Horizontal");
verticalInput = Input.GetAxis("Vertical");
if (Input.GetButton("Run"))
{
isRunning = true;
}
else if (Input.GetButtonUp("Run"))
{
isRunning = false;
}
//Makes player jump by returning a bool value to "yMovement()" when pressed.
if (Input.GetButtonDown("Jump"))
{
jumpRequest = true;
}
if (Input.GetKeyDown(KeyCode.A))
{
if (doubleTapTime > Time.time && lastKeyCode == KeyCode.A)
{
StartCoroutine(Dash(1f));
Debug.Log("You dashed left");
}
else
{
doubleTapTime = Time.time + 0.5f;
}
lastKeyCode = KeyCode.A;
}
if (Input.GetKeyDown(KeyCode.D))
{
if (doubleTapTime > Time.time && lastKeyCode == KeyCode.D)
{
StartCoroutine(Dash(-1f));
Debug.Log("You dashed right");
}
else
{
doubleTapTime = Time.time + 0.5f;
}
lastKeyCode = KeyCode.D;
}
}
void xMovement()
{
//Makes player walk left and right
if (!isRunning && !isDashing)
{
transform.Translate(Vector3.left * walkSpeed * horizontalInput * Time.deltaTime);
}
//Makes player run left and right
else if (isRunning && !isDashing)
{
transform.Translate(Vector3.left * runSpeed * horizontalInput * Time.deltaTime);
}
}
void yMovement()
{
//Make player jump when Jump is pressed
if (jumpRequest)
{
playerRb.velocity = new Vector3(playerRb.velocity.x, jumpForce);
jumpRequest = false;
//playerRb.velocity = new Vector2(playerRb.velocity.x, playerRb.velocity.y * jumpForce);
}
//Makes player fall faster in general, and when the Jump button is released
if (playerRb.velocity.y < 0)
{
playerRb.velocity += Vector3.up * Physics.gravity.y * (fallMultiplyer - 1) * Time.deltaTime;
}
else if (playerRb.velocity.y > 0 && !Input.GetButton("Jump"))
{
playerRb.velocity += Vector3.up * Physics.gravity.y * (lowJumpMultiplyer - 1) * Time.deltaTime;
}
}
IEnumerator Dash(float direction)
{
isDashing = true;
playerRb.velocity = new Vector3(playerRb.velocity.x, .0f);
playerRb.velocity = new Vector3(dashDistance * direction, 0f, 0f);
playerRb.useGravity = false;
yield return new WaitForSeconds(.2f);
isDashing = false;
playerRb.useGravity = true;
Any tips on code optimization is also greatly appreciated. I'm still fairly new to coding and would rather learn appropriate coding habits before I have to unlearn bad ones. Thank you!
I think your issue is that you're using a Translation on transform for the x axis when on the yAxis you're actually using the velocity. Unity might have trouble dealing with both in a single "FixedUpdate" call. Or it might just not do what you expect.
I would recommend sticking to velocity changes. So that would give something like
void xMovement()
{
//Makes player walk left and right
if (!isRunning && !isDashing)
{
playerRb.velocity += Vector3.left * walkSpeed * horizontalInput * Time.deltaTime;
}
//Makes player run left and right
else if (isRunning && !isDashing)
{
playerRb.velocity += Vector3.left * runSpeed * horizontalInput * Time.deltaTime;
}
}

my collision 2d doesn't work in C# on Unity

I'm learning C# while programming my game, I'm stuck doing the movement. I want my character to move continuously by pressing 'D' or 'A' once. Then, after colliding with an invisible wall while going to the right, go backwards until it hits another invisible wall and stop.
I managed to make my GameObject move, but when it collides with the wall, nothing happens. Both objects have a rigidbody2D, the same z-coordinates, and correct tags.
public class SquadMovement : MonoBehaviour {
float speed;
bool collisionRightWall = false;
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.D)) {
CancelInvoke ();
InvokeRepeating ("RightMovement", Time.deltaTime, Time.deltaTime);
}
if (Input.GetKeyDown (KeyCode.A)) {
CancelInvoke ();
InvokeRepeating ("LeftMovement", Time.deltaTime, Time.deltaTime);
}
}
void RightMovement () {
speed = 10f;
transform.Translate (speed * Time.deltaTime, 0, 0);
}
void LeftMovement () {
speed = -7f;
transform.Translate (speed * Time.deltaTime, 0, 0);
}
void OnCollisionWallR (Collider2D colR) {
if (colR.gameObject.tag == "invisibleWallRight") {
collisionRightWall = true;
Debug.Log (collisionRightWall);
}
}
}
I'm using invisible walls because I don't know how to use x-coordinates, There HAS to be a more efficient way but I want to know first why this don't work. I would be glad if someone could teach me that too.
using UnityEngine;
using System.Collections;
public class SquadMovement : MonoBehaviour {
float constantspeed = 3;
float speed;
//Key inputs
void Update () {
transform.Translate (constantspeed * Time.deltaTime, 0, 0);
if (Input.GetKeyDown (KeyCode.D)) {
StopAllCoroutines ();
StartCoroutine (RightMovement(0f));
}
if (Input.GetKeyDown (KeyCode.A)) {
StopAllCoroutines ();
StartCoroutine (LeftMovement(0f));
}
}
//Movement itself (Right, Left)
IEnumerator RightMovement (float Rloop) {
while (transform.position.x < Time.time * constantspeed + 6) {
speed = 10f;
transform.Translate (speed * Time.deltaTime, 0, 0);
yield return new WaitForSeconds (Rloop);
}
if (transform.position.x > Time.time * constantspeed + 5.9) {
StopAllCoroutines ();
StartCoroutine (LeftMovement (0f));
}
}
IEnumerator LeftMovement (float Lloop) {
while (transform.position.x > Time.time * constantspeed -8) {
speed = -7f;
transform.Translate (speed * Time.deltaTime, 0, 0);
yield return new WaitForSeconds (Lloop);
}
}
}

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