Unity 2D Jump script - c#

So I was trying to implement double jumping in my game, which doesn't work. And now, somehow, not only can't my players double jump, they can't even jump either!
update: they can jump now, still can't double jump though.
This is my whole movement script:
using UnityEngine;
namespace Players
{
public class Actor : MonoBehaviour
{
//in order to control both players using 1 script.
public int playerIdx;
//Variables.
public float movementSpeed = 150f;
public float jumpForce = 250f;
//Ground stuff.
public LayerMask whatIsGround;
public bool grounded;
//boolean stuff.
private bool facingRight;
private bool moving;
//Needed to check if player is on the ground.
public Transform groundCheck;
//Limit player's movement speed.
public float maxMovementSpeed = 400f;
//Double jump stuff.
private bool doubleJumpReady;
//rb
private Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
doubleJumpReady = true;
rb = GetComponent<Rigidbody2D>();
facingRight = true;
}
// Update is called once per frame
void FixedUpdate()
{
SlowDown();
}
private void LateUpdate()
{
grounded = Physics2D.OverlapCircle(groundCheck.position, 0.1f, whatIsGround);
if (grounded)
doubleJumpReady = true;
}
private void SlowDown()
{
if (moving) return;
//if player is not moving, slow them down.
if (rb.velocity.x > 0.2f)
rb.AddForce(movementSpeed * Time.deltaTime * -Vector2.right);
if (rb.velocity.x < -0.2f)
rb.AddForce(movementSpeed * Time.deltaTime * Vector2.right);
}
public void Move(int dir)
{
//Flip the player.
Flip(dir);
//Moving the player.
moving = true;
float xVel = rb.velocity.x; //Get x velocity.
if ( dir > 0)
rb.AddForce(movementSpeed * Time.deltaTime * Vector2.right * dir);
else if (dir < 0)
rb.AddForce(movementSpeed * Time.deltaTime * Vector2.right * dir);
else if (dir == 0) { } //do nothing.
//Help player turn around faster.
if (xVel > 0.2f && dir < 0)
rb.AddForce(movementSpeed * 3.2f * Time.deltaTime * -Vector2.right);
if (xVel < 0.2f && dir > 0)
rb.AddForce(movementSpeed * 3.2f * Time.deltaTime * Vector2.right);
}
private void Flip(int dir)
{
if (facingRight && dir == -1 || !facingRight && dir == 1)
{
facingRight = !facingRight;
transform.Rotate(0f, 180f, 0f);
}
}
protected void Jump()
{
if (grounded)
{
rb.AddForce(Vector2.up * jumpForce);
grounded = false;
doubleJumpReady = true;
}
else if (!grounded && doubleJumpReady)
{
rb.AddForce(Vector2.up * jumpForce);
doubleJumpReady = false;
}
}
}
}
I don't know if it is because of my jump script, or my player script:
void Update()
{
if (playerIdx == 1)
{
if (Input.GetKey(KeyCode.A))
Move(-1);
if (Input.GetKey(KeyCode.D))
Move(1);
if (Input.GetKey(KeyCode.W))
Jump();
}
if (playerIdx == 2)
{
if (Input.GetKey(KeyCode.LeftArrow))
Move(-1);
if (Input.GetKey(KeyCode.RightArrow))
Move(1);
if (Input.GetKey(KeyCode.UpArrow))
Jump();
}
}
So how can I fix this?

as far as i can see you never reset the
doubleJumpReady = false;
Variable. To fix this simply change the jump code to:
protected void Jump()
{
if (grounded)
{
rb.AddForce(Vector2.up * jumpForce);
grounded = false;
doubleJumpReady = true;
}
else if (!grounded && doubleJumpReady)
{
rb.AddForce(Vector2.up * jumpForce);
doubleJumpReady = false;
}
}
Hope it works ;).
EDIT:
grounded is set by overlapping spheres. Therefore no need to set it here.
Use this code and press your jump btn 2 times and see if the Debug.Log message shows up. Also, your player ID (idx is not needed.) As far as i can see your script is attached two to different objects. Therefore their variables are not shared anyways.
protected void Jump()
{
if (grounded)
{
rb.AddForce(Vector2.up * jumpForce);
doubleJumpReady = true;
}
else if (!grounded && doubleJumpReady)
{
rb.AddForce(Vector2.up * jumpForce);
doubleJumpReady = false;
Debug.Log("I am double jumping");
}
}
And the final problem is, you do not execute one of your jumps you execute both at once.
THis happens due to your execution.
Input.GetKey(KeyCode.UP)
instead use:
Input.GetKeyDown(KeyCode.Up);
GetKeyDown returns true when the button is pressed.
GetKey returns true WHILE the button is pressed.
Hope it works now ;)

I would implement it with a counter, you can set the number of jumps you want.
The code would be like this:
jumpCount = 0;
protected void Jump()
{
if(!grounded && jumpCount < 2)
{
jumpCount++;
rb.AddForce(Vector2.up * jumpForce);
}
if(grounded)
jumpCount = 0;
}

Going off the assumption that you can now perform the normal jump again after reading the comments. I think the reason you can't 'double jump' is that when you call the Jump() method, you don't just call it once, you call it twice, so what happens is the player jumps and then immediately double jumps and so you don't actually notice that the double jump has occurred. You could make it so that your doubleJumpReady boolean is only true after a set amount of time after you have jumped initially using some sort of co-routine or something I implemented for a sort of double jump mechanic once was that the user could press the jump button again to double jump only when the player had reached the maximum height of the initial jump or after.

Related

Infinite jump in unity 3D

My character keeps floating up if space bar is held down until you let go, I tried all day on how to make the character to jump normal but I am just stuck. I'm using unity to create the game. The issue started when I changed onfloor=true, before when it was false the character could only jump once. Here is the code for the character in C#
Thank you
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
private Transform rotateBody;
private Vector3 Direction;
private const float gravity = 0.1f;
private const float jump_force = 0.09f;
public Transform groundCheckTransform;
private bool shiftKeyWasPressed;
private bool jumpKeyWasPressed;
private float horizontalInput;
private Rigidbody RigidbodyComponent;
public LayerMask playerMask;
private int superJumpsRemaing;
private bool on_floor = true;
// Start is called before the first frame update
void Start()
{
RigidbodyComponent = GetComponent<Rigidbody>();
shiftKeyWasPressed = false;
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Space) & Direction.y > 0){
jumpKeyWasPressed = true;
}
horizontalInput = Input.GetAxis("Horizontal");
if(Input.GetKeyDown(KeyCode.LeftShift)){
shiftKeyWasPressed = true;
}
horizontalInput = Input.GetAxis("Horizontal");
}
void FixedUpdate(){
Direction.y -= gravity;
Direction.x = 0;
if (Input.GetKey(KeyCode.Space)){
if (Direction.y < 0 && on_floor){
Direction.y = 0;
}
if(on_floor){
Direction.y += jump_force*2;
on_floor = true;
}
}else{
jumpKeyWasPressed = false;
}
if (Input.GetKey(KeyCode.D)){
Direction.x += 2;
}
if (Input.GetKey(KeyCode.A)){
Direction.x -= 2;
}
if (Input.GetKey(KeyCode.LeftShift))
if(shiftKeyWasPressed==true)
Direction.x *= 6;
if(Physics.OverlapSphere(groundCheckTransform.position, 0.1f, playerMask).Length == 0){
return;
}
if (jumpKeyWasPressed)
{
float jumpPower = 7;
if (superJumpsRemaing > 0){
jumpPower *=2;
superJumpsRemaing--;
}
RigidbodyComponent.AddForce(Vector3.up*jumpPower, ForceMode.VelocityChange);
jumpKeyWasPressed = false;
}
RigidbodyComponent.velocity = Direction;
}
private void OnTriggerEnter(Collider other)
{
if ( other.gameObject.layer == 8){
jumpKeyWasPressed = true;
if(Direction.y > 8)
jumpKeyWasPressed = false;
}
if (other.gameObject.layer == 6){
Destroy(other.gameObject);
}
if (other.gameObject.layer == 7){
Destroy(other.gameObject);
superJumpsRemaing++;
}
}
}
Your on_floor variable never becomes false which results in constantly adding y value when ever space button is held down. You need to add the check for ground collision and set on_floor to false whenever player hits ground object. You can use raycast towards downward direction for this something like:
public dist = 10;
public RaycastHit hit;
public void CheckGroundBelow()
{
dist = 10; //Distance to calculate height from
dir = Vector3(0,-1,0); //Downward Direction
if(Physics.Raycast(transform.position,dir,hit,dist)){
on_floor = true;
}
else
{
on_floor = false;
}
}
Here it checks if something is below your player's transform . If there is something within 10 m then it means player is on ground otherwise it ignores input . You can call it just above your if condition here you check for on_floor.
More about Raycast here : https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
Alternatively you can also use Character Controller Component inside Unity which already has a check named as IsGrounded :
More about Character controller here : https://docs.unity3d.com/ScriptReference/CharacterController.html

Character doesn't jump sometimes - Unity

I am new to Unity and I am using the following CharacterController for my character. Everything is working well, except that sometimes the character jumps and sometimes it doesn't when I hit the spacebar. I used Debog.Log using Raycast to check if my character is grounded, and the result was True. So what is preventing my character from jumping whenever I hit the key?
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(CharacterController))]
public class RPGMovement : MonoBehaviour
{
public float ForwardSpeed = 8f;
public float BackwardSpeed = 4f;
public float StrafeSpeed = 5f;
public float RotateSpeed = 110f;
CharacterController m_CharacterController;
Vector3 m_LastPosition;
Animator m_Animator;
PhotonView m_PhotonView;
PhotonTransformView m_TransformView;
float m_AnimatorSpeed;
Vector3 m_CurrentMovement;
float m_CurrentTurnSpeed;
Vector3 playerVelocity;
private bool groundedPlayer;
private float jumpHeight = 0.9f;
private float gravityValue = -20.81f;
void Start()
{
m_CharacterController = GetComponent<CharacterController>();
m_Animator = GetComponent<Animator>();
m_PhotonView = GetComponent<PhotonView>();
m_TransformView = GetComponent<PhotonTransformView>();
}
void Update()
{
if (m_PhotonView.isMine == true)
{
ResetSpeedValues();
UpdateRotateMovement();
UpdateForwardMovement();
UpdateBackwardMovement();
UpdateStrafeMovement();
MoveCharacterController();
UpdateJump();
ApplySynchronizedValues();
}
UpdateAnimation();
}
void UpdateAnimation()
{
Vector3 movementVector = transform.position - m_LastPosition;
float speed = Vector3.Dot(movementVector.normalized, transform.forward);
float direction = Vector3.Dot(movementVector.normalized, transform.right);
if (Mathf.Abs(speed) < 0.2f)
{
speed = 0f;
}
if (speed > 0.6f)
{
speed = 1f;
direction = 0f;
}
if (speed >= 0f)
{
if (Mathf.Abs(direction) > 0.7f)
{
speed = 1f;
}
}
m_AnimatorSpeed = Mathf.MoveTowards(m_AnimatorSpeed, speed, Time.deltaTime * 5f);
m_Animator.SetFloat("Speed", m_AnimatorSpeed);
m_Animator.SetFloat("Direction", direction);
m_LastPosition = transform.position;
}
void ResetSpeedValues()
{
m_CurrentMovement = Vector3.zero;
m_CurrentTurnSpeed = 0;
}
void ApplySynchronizedValues()
{
m_TransformView.SetSynchronizedValues(m_CurrentMovement, m_CurrentTurnSpeed);
}
void MoveCharacterController()
{
m_CharacterController.Move(m_CurrentMovement * Time.deltaTime);
}
void UpdateForwardMovement()
{
if (Input.GetKey(KeyCode.W) || Input.GetAxisRaw("Vertical") > 0.1f)
{
m_CurrentMovement = transform.forward * ForwardSpeed;
}
}
void UpdateBackwardMovement()
{
if (Input.GetKey(KeyCode.S) || Input.GetAxisRaw("Vertical") < -0.1f)
{
m_CurrentMovement = -transform.forward * BackwardSpeed;
}
}
void UpdateStrafeMovement()
{
if (Input.GetKey(KeyCode.Q) == true)
{
m_CurrentMovement = -transform.right * StrafeSpeed;
}
if (Input.GetKey(KeyCode.E) == true)
{
m_CurrentMovement = transform.right * StrafeSpeed;
}
}
void UpdateRotateMovement()
{
if (Input.GetKey(KeyCode.A) || Input.GetAxisRaw("Horizontal") < -0.1f)
{
m_CurrentTurnSpeed = -RotateSpeed;
transform.Rotate(0.0f, -RotateSpeed * Time.deltaTime, 0.0f);
}
if (Input.GetKey(KeyCode.D) || Input.GetAxisRaw("Horizontal") > 0.1f)
{
m_CurrentTurnSpeed = RotateSpeed;
transform.Rotate(0.0f, RotateSpeed * Time.deltaTime, 0.0f);
}
}
void UpdateJump()
{
groundedPlayer = m_CharacterController.isGrounded;
if (groundedPlayer && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
if (Input.GetButtonDown("Jump") && groundedPlayer)
{
playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
m_Animator.SetTrigger("Jump");
print("Jumping Now");
}
playerVelocity.y += gravityValue * Time.deltaTime;
m_CharacterController.Move(playerVelocity * Time.deltaTime);
}
}
Best guess is that "m_PhotonView.isMine" is not returning true on the frames where you're missing input. It only checks jump input for that frame, so if the last frame you pressed it but jumping wasn't checked then that input is lost forever. First test this. Change the update code to this:
void Update()
{
if (Input.GetButtonDown("Jump")) { Debug.Log("Jump was pressed at {Time.time}"); }
if (m_PhotonView.isMine == true)
{
if (Input.GetButtonDown("Jump")) { Debug.Log("Attempting Jump at {Time.time}"); }
ResetSpeedValues();
UpdateRotateMovement();
UpdateForwardMovement();
UpdateBackwardMovement();
UpdateStrafeMovement();
MoveCharacterController();
UpdateJump();
ApplySynchronizedValues();
}
UpdateAnimation();
}
Then play the game and jump a bunch. The first debug log line should happen every time you click the spacebar no matter what. The second debug line would only happen if physics are calculated that frame. Both have times attached. Keep jumping until the jump doesn't work. If that jump only produces the first debug log and not the second, then I am correct and that is your issue.
If so, then it's an easy fix. Add a new bool variable called "jumpInput". Whenever you check if jump was pressed, instead check if "jumpInput" is true. Then, change update to this:
void Update()
{
if (Input.GetButtonDown("Jump")) { jumpInput = true; }
if (m_PhotonView.isMine == true)
{
ResetSpeedValues();
UpdateRotateMovement();
UpdateForwardMovement();
UpdateBackwardMovement();
UpdateStrafeMovement();
MoveCharacterController();
UpdateJump();
ApplySynchronizedValues();
jumpInput = false;
}
UpdateAnimation();
}
This way if you pressed jump, it's set to true... but it's only set to false after physics are done. So if you press jump on frame 20 and physics are somehow not calculated until frame 25, it'll still know that you pressed jump at some point and thus execute it. If you're using networking, you might want to also have another variable that's what frame jump was pressed. That way you can figure out how many frames it's been since input and compensate for missed time in the jump if necessary.

Changing a game objects velocity on button press in unity

So I'm trying to add a dash mechanic to a game character im building. However for some reason i can't get the game objects velocity to actually change. I tried using addForce which worked, but i had to add a lot in order to get the desired effect and that behaved strangely sometimes!
Do i need to do anything else to the game objects velocity than i already doing?
Heres my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float dashSpeed;
private int dashDirection;
private float dashCoolDown;
public float startDashCoolDown;
private float dashTime;
public float startDashTime;
public GameObject dashEffect;
public float speed;
public float jumpForce;
private float moveInput;
private Rigidbody2D rb;
private bool isFacingRight = true;
private Animator anim;
private bool isGrounded;
public Transform groundCheck;
public float checkRadius;
public LayerMask whatIsGround;
private int extraJumps;
public int extraJumpsValue;
public GameObject dustEffect;
public GameObject trailEffect;
private void Awake()
{
// Setting up references.
isGrounded = transform.Find("GroundCheck");
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
}
void Start()
{
extraJumps = extraJumpsValue;
rb = GetComponent<Rigidbody2D>();
dashTime = startDashTime;
dashCoolDown = startDashCoolDown;
}
void FixedUpdate()
{
isGrounded = false;
// Check to see if grounded
Collider2D[] colliders = Physics2D.OverlapCircleAll(groundCheck.position, checkRadius, whatIsGround);
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject != gameObject)
{
isGrounded = true;
anim.SetBool("Ground", isGrounded);
}
}
// Check if movement is allowed
if (!GameMaster.disableMovement)
{
// Move character
moveInput = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
Instantiate(trailEffect, groundCheck.position, Quaternion.identity);
anim.SetFloat("Speed", Mathf.Abs(moveInput));
}
// Flip character
if (isFacingRight == false && moveInput > 0)
{
Flip();
}
else if (isFacingRight == true && moveInput < 0)
{
Flip();
}
}
private void Update()
{
// Check if the player is grounded
if (isGrounded == true)
{
extraJumps = extraJumpsValue;
}
// Check if movement is allowed
if (!GameMaster.disableMovement)
{
// Check for jump
// If the player has more than one jump available
if (Input.GetKeyDown(KeyCode.Space) && extraJumps > 0)
{
isGrounded = false;
anim.SetBool("Ground", isGrounded);
rb.velocity = Vector2.up * jumpForce;
extraJumps--;
Instantiate(dustEffect, groundCheck.position, Quaternion.identity);
}
// If the player only has one jump available
if (Input.GetKeyDown(KeyCode.Space) && extraJumps == 0 && isGrounded == true)
{
isGrounded = false;
anim.SetBool("Ground", isGrounded);
rb.velocity = Vector2.up * jumpForce;
}
// Check for dash
if (dashCoolDown <= 0)
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
anim.SetBool("Dash", true);
Dash();
dashTime = startDashTime;
}
}
else
{
dashCoolDown -= Time.deltaTime;
}
}
}
void Dash()
{
if (dashTime <= 0)
{
dashCoolDown = startDashCoolDown;
anim.SetBool("Dash", false);
}
else
{
dashTime -= Time.deltaTime;
if (isFacingRight)
{
rb.velocity = Vector2.right * dashSpeed;
}
else if (!isFacingRight)
{
rb.velocity = Vector2.left * dashSpeed;
}
}
}
void Flip()
{
isFacingRight = !isFacingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
If you dont get the desired dash effect with Rigidbody.velocity, you can try using Rigidbody.addForce(). I know you said you already used it, but there are multiple different force modes you can apply here. I would suggest using this one, because it applies full force from the start and then drops it off. You can read more about it yourself here.
So you could modify your code like so:
void Dash()
{
if (isFacingRight)
{
rb.AddForce(Vector2.right*dashSpeed, ForceMode.VelocityChange);
}
else if (!isFacingRight)
{
rb.AddForce(Vector2.left*dashSpeed, ForceMode.VelocityChange);
}
}
Note, that you also dont need to call dash repeatedly to falloff the velocity. this function should now be only called onse the button to dash (shift) has been pressed.
Hope this helped!

A.I Companian turns when Player turns

I have a little companion that follows the player around, but he is also supposed to turn around when the player does. But instead, he constantly keeps turning could someone help me see where I went wrong
public float speed;
public float stoppingDistance;
private Transform target;
Player Player;
void Start()
{
Player = GameObject.Find("Axel").GetComponent<Player>();
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}
void Update()
{
if (Vector2.Distance(transform.position, target.position) > stoppingDistance)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
if (Player.facingRight == false)
{
Turn();
}
else if (Player.facingRight == true)
{
Turn();
}
}
}
void Turn()
{
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
Well you call Turn "all the time" but you never check if you probably already are looking in the correct direction ...
either change your condition or add a parameter to Turn and set a fixed direction instead of toggling between two directions without controlling which is the current direction.
You could do it e.g. with an enum Direction like
public float speed;
public float stoppingDistance;
private Transform target;
Player Player;
private enum Direction
{
right = 1,
left = -1;
}
// for storing the scale on start
private Vector3 originalScale;
private void Start()
{
Player = GameObject.Find("Axel").GetComponent<Player>();
// If you just want the transform of the Player
// than simply use
target = Player.transform;
// instead of
//target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
originalScale = transform.localScale;
}
// Btw: for reacting to any user input (as the player movement)
// it is always better to do these things
// in LateUpdate instead of Update
// LateUpdate is executed after all Update calls in the Scene finished
private void LateUpdate()
{
if (Vector2.Distance(transform.position, target.position) > stoppingDistance)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
if (Player.facingRight == false)
{
Turn(Direction .left);
}
else if (Player.facingRight == true)
{
Turn(Direction .right);
}
}
}
private void Turn(Direction direction)
{
transform.localScale = Vector3.Scale(originalScale, Vector3.right * (int)direction);
}
As alternative if you want to keep your original Turn you could as well simply add more conditions before you even call Turn. Something like
// ...
if (Player.facingRight == false && transform.localScale.x > 0)
{
Turn();
}
else if (Player.facingRight == true && transform.localScale.x < 0)
{
Turn();
}
// ...
private void Turn()
{
transform.localScale = Vector3.Scale(transform.localScale, -Vector3.right);
}

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