I'm new to coding and I've been playing around with unity and I've encountered a problem.
My problem is, if I move the player and activate the function SkillAttack1, the animation will cancel out and won't complete. Right now, as you see in the code belowif I activate theSkillAttack1`, it works, but still it won't complete the animation. Also, if I'm pressing the "w" button, for example, for 15 seconds the player gets stuck and moves forward. The only way to play the full animation is not moving, but that's not right.
[Animator1][1]
[Animator2][2]
[Animator3][3]
[1]: https://i.stack.imgur.com/BeziY.png
[2]: https://i.stack.imgur.com/310vz.png
[3]: https://i.stack.imgur.com/tOVVu.png
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float velocity = 5;
public float turnSpeed = 10;
Vector2 input;
float angle;
Quaternion targetRotation;
public Transform cam;
public Animator anim;
public bool IsAttacking = false;
void Start()
{
anim = GetComponent<Animator>();
}
void Update()
{
if(Mathf.Abs(input.x) < 0.5 && Mathf.Abs(input.y) < 0.5) return;
CalculateDirection();
Rotate();
Move();
}
void FixedUpdate()
{
if(IsAttacking == false)
{
GetInput();
}
SkillAttack1();
SkillAttack2();
}
/// Input based on Horizontal(a,d) and Vertical (w,s) keys
void GetInput()
{
input.x = Input.GetAxis("Horizontal");
input.y = Input.GetAxis("Vertical");
anim.SetFloat("VelX", input.x);
anim.SetFloat("VelY", input.y);
}
/// Direction relative to the camera rotation
void CalculateDirection()
{
angle = Mathf.Atan2(input.x, input.y);
angle = Mathf.Rad2Deg * angle;
angle += cam.eulerAngles.y;
}
/// Rotate toward the calculated angle
void Rotate()
{
targetRotation = Quaternion.Euler(0, angle, 0);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, turnSpeed
* Time.deltaTime);
}
/// This player only move along its own forward axis
void Move()
{
transform.position += transform.forward * velocity * Time.deltaTime;
}
public void SkillAttack1(){
if(Input.GetKeyDown("1"))
{
IsAttacking = true;
StartCoroutine(OnSkillAttack1());
}
}
public void SkillAttack2()
{
if(Input.GetKeyDown("2"))
{
anim.SetTrigger("SkillAttack2");
}
}
public IEnumerator OnSkillAttack1()
{
anim.SetTrigger("SkillAttack1");
yield return null;
yield return new WaitForSeconds(15.0f);
IsAttacking = false;
}
}
Looks like your animation controller is getting overridden by your movement code, when your player sends some input to walk left or right, it sets the VelX and VelY variables on your animation controller. Without access to your controller I can't tell you exactly why it's interrupting the attack, but it's likely you have an interrupt set up that triggers from "any state" when one of those variables is above 0 and transitions into the "walk" animation your controller has.
You'll need to adjust your animation transitions to handle this potential case, or alternatively, prevent movement code triggering during an attack animation.
Related
I'm trying to make a 2D top-down shooter in Unity. I want it so when the you hold down the left mouse button the player fires a series of bullets until you run out of ammo. The player's movement speed is slowed while firing and the players movement speed should be added to the bullet's movement speed. For some reason the players movement speed is only applied to the bullets AFTER the first bullet is fired. The first bullet always seems to keep the slightly faster 'sprint' movement speed.
Weapon script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : MonoBehaviour
{
private GameObject bulletPrefab;
private Transform firePoint;
private PlayerControls player;
public float fireForce = 10f;
private bool cooldown = false;
private int bullets;
public int bulletDamage;
public int maxAmmo;
public float fireRate = 0.5f;
public float reloadRate = 2.5f;
public bool noAmmo = false;
public float walkSpeed = 2f;
private float timeSinceLastShot = 0f;
void Update()
{
// increase time since last shot
timeSinceLastShot += Time.deltaTime;
// if left-click is held down
if (Input.GetMouseButton(0))
{
// if enough time has passed since last shot
if (timeSinceLastShot >= fireRate && noAmmo == false)
{
player.moveSpeed = walkSpeed;
bullets -= 1;
cooldown = true;
if (bullets <= 0)
{
noAmmo = true;
player.moveSpeed = player.baseSpeed;
}
// instantiate a bullet
GameObject bullet = Instantiate(bulletPrefab, firePoint.transform.position, Quaternion.identity);
bullet.GetComponent<Bullet>().bulletDamage = bulletDamage;
// add player movement speed to bullet's speed
bullet.GetComponent<Rigidbody2D>().velocity = player.GetComponent<Rigidbody2D>().velocity;
bullet.GetComponent<Rigidbody2D>().AddForce(transform.up * fireForce, ForceMode2D.Impulse);
// reset time since last shot
timeSinceLastShot = 0f;
}
}
// if left-click is not held down
else
{
cooldown = false;
// restore player movement speed
player.moveSpeed = player.baseSpeed;
}
}
public void FillMag()
{
bullets = maxAmmo;
noAmmo = false;
}
}
PlayerControls:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControls : MonoBehaviour
{
public float moveSpeed = 5f;
public float baseSpeed = 5f;
public int health;
public Weapon weapon;
private Rigidbody2D rb;
Vector2 mousePosition;
Vector2 moveDirection;
public float walkSpeed = 2f;
void Update()
{
float moveX = Input.GetAxisRaw("Horizontal");
float moveY = Input.GetAxisRaw("Vertical");
moveDirection = new Vector2(moveX, moveY).normalized;
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
rb.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);
Vector2 aimDirection = mousePosition - rb.position;
float aimAngle = Mathf.Atan2(aimDirection.y, aimDirection.x) * Mathf.Rad2Deg - 90f;
rb.rotation = aimAngle;
}
}
The player is moving from left to right.
Player firing
According to Unity's lifecycle, inputs are only calculated just before the Update method is called, but physics are applied during the FixedUpdate method. Is this what is causing my problems? I've tried moving some calculations into FixedUpdate and LateUpdate but nothing seems to make any difference.
Any help is appreciated. I've been banging my head against this for a few days now. I'm an amature, so feel free to explain like I'm 5.
So there are 2 problems with your code:
if you are not holding down left mouse, but multiple click instead:
the else statement in the Update() will immediately set it player back to base speed, which is not really matter if you intent to holding your mouse.
There are 2 concurrent things happen
first, you set player moveSpeed in Weapon Update()
at the same time, you calculate player velocity in Player Update()
But it TAKES TIME for player to update velocity before you get it right to your weapon.
Therefore, I recommend you to use IEnumerator to delay the fire action.
public class Weapon : MonoBehaviour
{
void FixedUpdate()
{
// increase time since last shot
timeSinceLastShot += Time.deltaTime;
// if left-click is held down
if (Input.GetMouseButton(0))
{
// if enough time has passed since last shot
if (timeSinceLastShot >= fireRate && noAmmo == false)
{
//player.moveSpeed = walkSpeed;
StopAllCoroutines();
StartCoroutine(SetSpeed());
bullets -= 1;
cooldown = true;
if (bullets <= 0)
{
noAmmo = true;
player.moveSpeed = player.baseSpeed;
}
// instantiate a bullet
StartCoroutine(FireBulelt());
// reset time since last shot
timeSinceLastShot = 0f;
}
}
// if left-click is not held down
}
IEnumerator SetSpeed()
{
player.moveSpeed = walkSpeed;
yield return new WaitForSeconds(0.5f);
cooldown = false;
// restore player movement speed
player.moveSpeed = player.baseSpeed;
yield return null;
}
IEnumerator FireBulelt()
{
yield return new WaitForSeconds(0.05f);
GameObject bullet = Instantiate(bulletPrefab, player.transform.position, Quaternion.identity);
print(" player.GetComponent<Rigidbody2D>().velocit " + player.GetComponent<Rigidbody2D>().velocity);
// add player movement speed to bullet's speed
Rigidbody2D bulletRB = bullet.GetComponent<Rigidbody2D>();
print(" bulletRB.velocit " + bulletRB.velocity);
bulletRB.velocity = player.GetComponent<Rigidbody2D>().velocity;
print(" after bulletRB.velocit " + bulletRB.velocity);
bulletRB.AddForce(transform.up * fireForce, ForceMode2D.Impulse);
}
}
And you should add print() like I did to keep track of code behavior when you're debugging.
Hi I am currently learning from the book (Learning c# by developing games with unity 2021).
1.Right now in the game I have created a bullet object this object is supposed to be destroyed after being created.
2.But since I want to display it in the scene for a time I created a floating point to see how much time I can give. I applied these are parameters in the destroy utility function.
problem:-
1.Instead of destroying it after a certain time it deleted it entirely after it was created.
This is a problem the code I wrote to create the bullet is attached to my player.
2.It deletes the prefab in the starting of the game itself
Player action:-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerBehavoiur : MonoBehaviour
{
//this is a bullet made and used
public GameObject Bullet;
//the speed with the bullet
public float BulletSpeed = 100f;
//checks if our player is shooting
private bool _isShooting;
//stores the desired distance to ground
public float distanceToGround = 0.1f;
//creates a reference variable of type layermask
public LayerMask GroundLayer;
//gets the collider stored in a variable that will be used to access it
private CapsuleCollider _col;
void Update()
{
/*MoveForward(_hInput1);
RotateUpWards(_vInput1);
*/
_isJumping |= Input.GetKeyDown(KeyCode.Space);
PrintIfJumping(_isJumping);
//this sets it to a method that checks if the key in the
//arguments pressed down on
IsFalling |= Input.GetKeyDown(KeyCode.G);
//scans for mouse input and sets the isShooting field to that value
//if that value is true or when the mouse is clicked then run the shoot method
//this is through prefabs which are are used
_isShooting |= Input.GetMouseButtonDown(0);
}
void PrintIfJumping(bool _isJumping)
{
if (_isJumping == true)
{
Debug.Log("Time to take a leap of faith!");
}
else
{
Debug.Log("Im on the ground this sucks!");
}
}
void Start()
{
_rb = GetComponent<Rigidbody>();
_rb.useGravity = true;
//sets isJumping to keycode.space which checks wether the key space is pressed
//gets the collider component and stores inside a variable for later use
_col = GetComponent<CapsuleCollider>();
}
void SetVerticalDirection()
{
_vInput1 = Input.GetAxis("Vertical") * MoveSpeed;
}
void SetHorizontalDirection()
{
_hInput1 = Input.GetAxis("Horizontal") * RotateSpeed;
}
public float MoveSpeed = 10f;
public float RotateSpeed = 75f;
public int hp = 0;
/// <summary>
/// stores a rigidbody component for a gameobject
/// </summary>
private Rigidbody _rb;
public float JumpVelocity = 5f;
private bool _isJumping;
private bool IsFalling;
public float FallVelocity;
/// <summary>
/// Start is called before the first frame update
/// </summary>
private float _hInput1;
private float _vInput1;
/// <summary>
/// Update is called once per frame
/// </summary>
/*public void MoveForward(float _vInput)
{
_vInput = Input.GetAxis("Vertical") * MoveSpeed;
this.transform.Translate()
}
public void RotateUpWards(float _hInput)
{
_hInput = Input.GetAxis("Horizontal") * RotateSpeed;
this.transform.Translate(Vector3.forward * _hInput * Time.deltaTime);
}
*/
void FixedUpdate()
{
SetVerticalDirection();
SetHorizontalDirection();
//makes the object move by horizontal input in the up direction
Vector3 rotation = Vector3.up * _hInput1;
/*this is the rotation of the game object
* moving up and then going at a fixed frame rate
*/
Quaternion angleRotation = Quaternion.Euler(rotation * Time.fixedDeltaTime);
//this takes vertical input and addes the position and makes it move forward
//the vertical input is the vertical axis whihc moves at a defined rate tht we can define
_rb.MovePosition(this.transform.position +
this.transform.forward * _vInput1 * Time.fixedDeltaTime);
/*the move rotation moves using the rigibody rotation times the
* horizontal input times and moves up and rotates at the rotate speed rate
*/
_rb.MoveRotation(_rb.rotation * angleRotation);
//performs a jump if object is in collision with ground and isJumping
if(IsGrounded() && _isJumping)
{
/*while(JumpVelocity > 0)
{
--JumpVelocity;
}
*/
_rb.AddForce(Vector3.up * JumpVelocity, ForceMode.Impulse);
}
Fall(IsFalling);
Shoot(_isShooting, Bullet);
}
private bool IsGrounded() {
//this defines the bottom of the capsule or the end
Vector3 capsuleBottom = new Vector3(_col.bounds.center.x, _col.bounds.min.y, _col.bounds.center.z);
//this checks if a object is touching start or bottom of a capsule and the raduis is distance to ground
//this sets the ground layer to the phy-system
bool grounded = Physics.CheckCapsule(_col.bounds.center, capsuleBottom, distanceToGround, GroundLayer, QueryTriggerInteraction.Ignore);
return grounded;
}
public void Fall(bool grounded)
{
bool Gpressed = Input.GetKeyDown(KeyCode.G);
Debug.Log("G is pressed");
Debug.LogFormat("The down direction is {0}", Vector3.down);
if (Gpressed ==true & grounded == false)
{
_rb.AddForce(Vector3.down * FallVelocity, ForceMode.Impulse);
}
else
{
Debug.Log("No falling allowed!");
}
}
public void Shoot(bool _isShooting,GameObject Bullet)
{
if (_isShooting == true)
{
//this is the instance of the prefab bullet which is created using the unity editor
//builds
GameObject newBullet = Instantiate(Bullet, this.transform.position + new Vector3(1, 0, 0), this.transform.rotation);
//create a new bullet rigidbody which captures the component rb
Rigidbody BulletRB = newBullet.GetComponent<Rigidbody>();
//set the velocity (speed x direction) basically
//so we want our bullet to go forward x a certian speed so...
BulletRB.velocity = this.transform.forward * BulletSpeed;
}
_isShooting = false;
}
/*Horizontal: ad
* Vertical: ws */
}
Its pretty long I know just read the shoot function and the stuff in update on shooting
So the bullet behaviour is:-
public class BulletBehaviour : MonoBehaviour
{
float OnScreenDelay = 3f;
void Start()
{
Destroy(this.gameObject,OnScreenDelay);
}
// Update is called once per frame
void Update()
{
}
public void Scale(float x, float y, float z)
{
this.transform.localScale = new Vector3(x, y, z);
}
}
I've been recently working on a project using Unity Engine that involves a sort of Top-Down, 3rd person view, and I have been having trouble with the character movement.
I want to implement a way for the player to move throughout the map using either WASD movement, Click-to-Move movement, or Drag-to-Move movement, allowing them to use either of these freely and at any time, yet I have not yet found a way of doing this, since the methods end up cancelling each other out, leading the Player Character to awkward movement and to getting stuck in place.
Is there any way of achieving this? If so, any tips/suggestions would be greatly appreciated. Please keep in mind I am a complete beginner when it comes to both Unity and C#, so I might not grasp some core concepts yet.
I have attached my PlayerMovement C# code below.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
[RequireComponent(typeof(test))]
public class PlayerMovement : MonoBehaviour
{
private test _input;
//click2move
private NavMeshAgent agent;
//x
[SerializeField]
private bool RotateTowardMouse;
[SerializeField]
private float MovementSpeed;
[SerializeField]
private float RotationSpeed;
[SerializeField]
private Camera Camera;
void Start()
{
//c2m
agent = GetComponent<NavMeshAgent>();
//x
}
private void Awake()
{
_input = GetComponent<test>();
}
// Update is called once per frame
void Update()
{
var targetVector = new Vector3(_input.InputVector.x, 0, _input.InputVector.y);
var movementVector = MoveTowardTarget(targetVector);
agent.autoBraking = true;
if (!RotateTowardMouse)
{
RotateTowardMovementVector(movementVector);
}
if (RotateTowardMouse)
{
RotateFromMouseVector();
}
//c2m
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (Input.GetMouseButtonDown(0))
{
agent.SetDestination(hit.point);
}
}
else
{
if (agent.remainingDistance < 1)
{
agent.ResetPath();
}
}
}
private void RotateFromMouseVector()
{
Ray ray = Camera.ScreenPointToRay(_input.MousePosition);
if (Physics.Raycast(ray, out RaycastHit hitInfo, maxDistance: 300f))
{
var target = hitInfo.point;
target.y = transform.position.y;
transform.LookAt(target);
}
}
private Vector3 MoveTowardTarget(Vector3 targetVector)
{
var speed = MovementSpeed * Time.deltaTime;
// transform.Translate(targetVector * (MovementSpeed * Time.deltaTime)); Demonstrate why this doesn't work
//transform.Translate(targetVector * (MovementSpeed * Time.deltaTime), Camera.gameObject.transform);
targetVector = Quaternion.Euler(0, Camera.gameObject.transform.rotation.eulerAngles.y, 0) * targetVector;
var targetPosition = transform.position + targetVector * speed;
transform.position = targetPosition;
return targetVector;
}
private void RotateTowardMovementVector(Vector3 movementDirection)
{
if (movementDirection.magnitude == 0) { return; }
var rotation = Quaternion.LookRotation(movementDirection);
transform.rotation = Quaternion.RotateTowards(transform.rotation, rotation, RotationSpeed);
}
}
I would highly recommend that you use the Unity Input System. It can automate switching between input devices and decouple your code from any specific controls. It might be a bit overwhelming if you have limited experience with C#, but there is a vast library of tutorial videos and written guides you can rely on.
The PlayerInput component is what detects when different input devices are added or removed and switches to the first valid control scheme. When a user activates the inputs required to trigger something in your game, that is represented as an Action. A set of callbacks for that action are called depending on the states of the input: started, performed, and canceled. These are where you hook up your character controller to the input and run any extra logic necessary to turn an input into movement. The Input System also has a feature called interactions that will probably be useful, especially for drag-to-move controls.
Good luck! If you'd like me to explain something further or point you to a good tutorial, feel free to tag me in a comment.
First create a Capsule in the scene, drag the main camera to its object, hang the script under the Capsule object, WASD controls the movement direction, the space moves up along the Y axis, and the F moves down along the Y axis, thank you
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveCam : MonoBehaviour
{
private Vector3 m_camRot;
private Transform m_camTransform;//Camera Transform
private Transform m_transform;//Camera parent object Transform
public float m_movSpeed=10;//Movement factor
public float m_rotateSpeed=1;//Rotation factor
private void Start()
{
m_camTransform = Camera.main.transform;
m_transform = GetComponent<Transform>();
}
private void Update()
{
Control();
}
void Control()
{
if (Input.GetMouseButton(0))
{
//Get the mouse movement distance
float rh = Input.GetAxis("Mouse X");
float rv = Input.GetAxis("Mouse Y");
// rotate the camera
m_camRot.x -= rv * m_rotateSpeed;
m_camRot.y += rh*m_rotateSpeed;
}
m_camTransform.eulerAngles = m_camRot;
// Make the main character face in the same direction as the camera
Vector3 camrot = m_camTransform.eulerAngles;
camrot.x = 0; camrot.z = 0;
m_transform.eulerAngles = camrot;
// Define 3 values to control movement
float xm = 0, ym = 0, zm = 0;
//Press W on the keyboard to move up
if (Input.GetKey(KeyCode.W))
{
zm += m_movSpeed * Time.deltaTime;
}
else if (Input.GetKey(KeyCode.S))//Press keyboard S to move down
{
zm -= m_movSpeed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.A))//Press keyboard A to move left
{
xm -= m_movSpeed * Time.deltaTime;
}
else if (Input.GetKey(KeyCode.D))//Press keyboard D to move right
{
xm += m_movSpeed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.Space) && m_transform.position.y <= 3)
{
ym+=m_movSpeed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.F) && m_transform.position.y >= 1)
{
ym -= m_movSpeed * Time.deltaTime;
}
m_transform.Translate(new Vector3(xm,ym,zm),Space.Self);
}
}
I'm making an enemy in my 2D Unity game, and I was trying to flip the sprite when it faces the opposite direction, the thing is, the sprite would only flip when the player was very close to the enemy. This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMovement : MonoBehaviour
{
public float moveSpeed;
private PlayerMovement player;
public float playerRange;
public LayerMask playerLayer;
public bool playerinRange;
private bool Right = false;
private void Start()
{
player = FindObjectOfType<PlayerMovement>();
}
private void Update()
{
playerinRange = Physics2D.OverlapCircle(transform.position, playerRange, playerLayer);
if (playerinRange)
{
transform.position = Vector3.MoveTowards(transform.position, player.transform.position, moveSpeed * Time.deltaTime);
}
Flip();
}
private void OnDrawGizmosSelected()
{
Gizmos.DrawSphere(transform.position, playerRange);
}
private void Flip()
{
if (transform.position.x > 0 && !Right || transform.position.x < 0 && Right)
{
Right = !Right;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
}
Looking at your code, what's happening is that the direction the enemy is facing is dependent of the position of the enemy in the world (since you are using the x component of transform.position). If your enemy x position is positive, the Right boolean will be true, otherwise it will be false (also the 0 case isn't accounted for).
Since the only thing that can move the enemy in this code snippet is the Vector3.MoveToward when the player is in range, I suspect what's happening is that as your player gets close, the enemy moves and the x position value goes from negative to positive (or the opposite), flipping the sprite.
Now, linking the sprite direction to the enemy's position isn't something you want to do. Instead, you want the enemy to face the direction it is moving toward. This can be done by having a velocity parameter that you use to move your enemy and which will tell you in which direction he is moving (and at which speed) for instance. If you want to keep the move toward, then you need to figure out in which direction it is making you move and flip the sprite accordingly. Here is a code example base on your code:
private void Update()
{
playerinRange = Physics2D.OverlapCircle(transform.position, playerRange, playerLayer);
if (playerinRange)
{
transform.position = Vector3.MoveTowards(transform.position, player.transform.position, moveSpeed * Time.deltaTime);
Flip(player.transform.position.x - transform.position.x);
}
}
private void Flip(float direction)
{
Right = (direction >= 0);
Vector3 theScale = transform.localScale;
theScale.x = Mathf.Abs(theScale.x) * Mathf.Sign(direction);
transform.localScale = theScale;
}
I have a little problem with my player control script (C#) in the unity enigne. I worked out the following script with the basic movement of the player. The problem is that the player can enter the jump statement (the debug log printed it out)
Debug Log
but it will not work. The character is still on the ground.
The jump function will be enabled when the player is on the ground (grounded) and did not a double jump.
So my question is are there any "code mistakes" or maybe some configuration problems which I do not see?
Thank you for your help in advance!
using UnityEngine;
using System.Collections;
public class PlayerControl : MonoBehaviour
{
// public variables
public float speed = 3f;
public float jumpHeight = 5f;
// private variables
Vector3 movement;
Animator anim;
Rigidbody2D playerRigidbody;
// variables for the ground check
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask whatIsGround;
private bool grounded;
private bool doubleJump;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
// Proves if the player is on the ground and activate the double jump function
if (grounded)
{
doubleJump = false;
}
// First line of proving the jump
if (Input.GetMouseButtonDown(0) && grounded)
{
Debug.Log("Jump if entered");
Jump();
}
if (Input.GetMouseButtonDown(0) && !doubleJump && !grounded)
{
Debug.Log("double Jump");
Jump();
doubleJump = true;
}
// Flipping the Player when he runs back
if (Input.GetAxis("Horizontal") < 0)
{
playerRigidbody.transform.localScale = new Vector2(-1.7f, 1.7f);
}
else
{
playerRigidbody.transform.localScale = new Vector2(1.7f, 1.7f);
}
}
void Awake()
{
// References setting up
playerRigidbody = this.GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
void FixedUpdate()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
// simple Movement without a speed control
Move(horizontal, vertical);
Animating(horizontal, vertical);
// Section for ground detection
grounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
// Set the parameter for the jump animation false or true
anim.SetBool("Grounded", grounded);
}
void Move(float horizontal, float vertical)
{
movement.Set(horizontal, 0f, vertical);
movement = movement.normalized * speed * Time.deltaTime;
playerRigidbody.MovePosition(transform.position + movement);
}
void Jump()
{
playerRigidbody.AddForce(Vector3.up * jumpHeight);
// playerRigidbody.AddForce(new Vector2(0f, jumpHeight), ForceMode2D.Impulse);
Debug.Log("Jump function");
}
void Animating(float h, float v)
{
bool walking = h != 0f || v != 0f;
anim.SetBool("IsWalking", walking);
}
}
Just guessing here, but maybe Vector3.up does not work for 2D physics? I'm not really into 2D, but you could try
playerRigidbody.AddForce(transform.up * jumpHeight);
instead.
Also, have you tried different values for jumpHeight? 5 might be way to small depending on the mass you set for your rigidbody.
And make sure you haven't restricted any axes in the inspector.
// Note: If you want the object to move in a reliable predictable way but still allow physics interactions, use MovePosition (set the object to kinematic if you want it to be unaffected by physics but still be able to affect other things, and uncheck kinematic if you want both objects to be able to be acted on by physics.
If you want to move your object but let physics handle the finer details, add a force.
playerRigidbody.rigidbody2D.AddForce(Vector3.up * 10 * Time.deltaTime);
use Vector.up, Vector.down, vector.right, Vectore.left along with time.deltaTime to have smooth movement along the frame.