When the player is grounded plays the falling and landing animation in an eternal loop - unity3d

Capsule Collider height: 2; Capsule Collider radius: 0.5 While the
player is rgounded the Grounded the Falling and Grounded parameters
turn on and off continuously. This is the project (unity package)
Conditions: From Movements to Jump, Jump parameter has to be
triggered. From Jump to Falling, Falling parameter has to be true.
From Falling to Landing, Grounded parameter has to be true. From
Movements to Falling, Falling parameter has to be true.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Game.Manager;
public class PlayerController : MonoBehaviour
{
InputManager inputManager;
Animator animator;
Rigidbody playerRb;
CapsuleCollider collider;
bool hasAnimator;
bool grounded;
[SerializeField] float jumpFactor = 250f;
float Dis2Ground;
[SerializeField] LayerMask GroundCheck;
[SerializeField] float airResistance = 0.8f;
void Start()
{
collider = GetComponent<CapsuleCollider>();
Dis2Ground = collider.bounds.extents.y;
inputManager = GetComponent<InputManager>();
playerRb = GetComponent<Rigidbody>();
hasAnimator = TryGetComponent<Animator>(out animator);
fallingHash = Animator.StringToHash("Falling");
jumpHash = Animator.StringToHash("Jump");
groundHash = Animator.StringToHash("Grounded");
}
private void FixedUpdate()
{
HandleJump();
SampleGround();
}
private void HandleJump()
{
if (!hasAnimator) return;
if (!inputManager.Jump) return;
animator.SetTrigger(jumpHash);
}
public void JumpAddForce()
{
playerRb.AddForce(Vector3.up * jumpFactor, ForceMode.Impulse);
playerRb.AddForce(-playerRb.velocity.y * Vector3.up, ForceMode.VelocityChange);
animator.ResetTrigger(jumpHash);
}
private void SampleGround()
{
if (!hasAnimator) return;
RaycastHit hitInfo;
if(Physics.Raycast(transform.position, Vector3.down, out hitInfo, Dis2Ground + 0.1f))
{
grounded = true;
SetAnimationGrounding();
return;
}
Debug.Log(grounded);
animator.SetFloat(zVelHash, playerRb.velocity.y);
grounded = false;
SetAnimationGrounding();
return;
}
private void SetAnimationGrounding()
{
animator.SetBool(fallingHash, !grounded);
animator.SetBool(groundHash, grounded);
}
}

Related

How to spawn multiple prefab, with individual physics

I Did apply some of the responses , most likely in the wrong way.. this is still not working with this RAYCAST. What am I doing wrong here?
Want to spawn a prefab, which is a a ball, this ball is flying forward on flick finger on the screen.
What I want is to spawn OnClick FEW/Multiple of this prefab.
, prefab is spawning on Raycast Hit, BUT.. when I am flicking the object EVERY prefab in the scene is moving in the same way.
If I flick first one in to the Left, it goes there, but If now I flick second one to right, BOTH go to the RIGHT, but I would like them to work independent. Maybe this is easy fix to this but I can't find answer. (I'm planning to have up to 30/50 of this prefabs, so attaching separate scripts would be bit time consuming)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallScript1 : MonoBehaviour
{
Vector2 startPos, endPos, direction;
float touchTimeStart, touchTimeFinish;
public float timeInterval = 5f;
public float throwForceInXandY = 1f;
public float throwForceinZ = 40f;
public static bool SpawnButtonAppear = true;
public static bool thrown = false;
public static bool moving = false;
public static bool fly = false;
public bool Pressed = false;
Rigidbody rb;
public GameObject player;
public Vector3 originalPos;
public GameObject playerPrefab;
string touched;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.isKinematic = true;
}
private void OnMouseDown()
{
PlayerTest.clicked = true;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit _hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out _hit))
{
touched = _hit.collider.tag;
if (touched == "Player")
{
Invoke("spawned", 0.5f);
}
}
}
if (touched == "Player")
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
touchTimeStart = Time.time;
startPos = Input.GetTouch(0).position;
}
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
{
fly = false;
touchTimeFinish = Time.time;
endPos = Input.GetTouch(0).position;
direction = startPos - endPos;
rb.isKinematic = false;
rb.AddForce(-direction.x * throwForceInXandY, -direction.y * throwForceInXandY, throwForceinZ * timeInterval);
BackWall.canSpawnNow = 1;
}
}
}
public void spawned()
{
GameObject spawnedprefab = Instantiate(playerPrefab, new Vector3(originalPos.y, originalPos.x, originalPos.z), Quaternion.identity);
Destroy(spawnedprefab, 5f);
}
The thrown variable is not declared inside your class, so when you set it to true you are setting it true for all the instances of the class.
Declare the bool thrown; inside the EnemySpawn class, so that OnMouseDown, only the corresponding intance's thrown variable is set to true.

Why does my charakter in unity gets stuck in the tilemap?

In my Unity my Player gets everytime stuck in the collider when he has a big force (If he falls from a high place, The Gravity Scale or his jumppower is high). In the picture you can see Colliders and Renderer.
Only one Component is not on in screen at the platformcomponents, Tilemap.
Here is my code for Playermovement:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField] private LayerMask platformsLayerMask;
private Rigidbody2D rigidbody2d;
private BoxCollider2D boxCollider2d;
private void Awake()
{
rigidbody2d = transform.GetComponent<Rigidbody2D>();
boxCollider2d = transform.GetComponent<BoxCollider2D>();
}
private void Update()
{
if (IsGrounded() && Input.GetKeyDown(KeyCode.Space))
{
float jump_power = 17.5f;
rigidbody2d.velocity = Vector2.up * jump_power;
}
HandleMovement();
}
private bool IsGrounded()
{
RaycastHit2D raycastHit2d = Physics2D.BoxCast(boxCollider2d.bounds.center, boxCollider2d.bounds.size, 0f, Vector2.down, .1f, platformsLayerMask);
return raycastHit2d.collider != null;
}
private void HandleMovement()
{
float moveSpeed = 10f;
if (Input.GetKey(KeyCode.A))
{
rigidbody2d.velocity = new Vector2(-moveSpeed, rigidbody2d.velocity.y);
}
else if (Input.GetKey(KeyCode.D))
{
rigidbody2d.velocity = new Vector2(+moveSpeed, rigidbody2d.velocity.y);
}
else
{
rigidbody2d.velocity = new Vector2(0, rigidbody2d.velocity.y);
}
}
}
Have you tried setting the player's rigidbody collision detection to continuous? If the collision detection is set to discrete, it's really easy to come accross this kind of problem when using the built in physics system

Stop an Object if it reached the transform value

So I have a 2d gameObject that behaves likes a spike trap that springs out of the ground when the character collides on the trigger. I use AddForce to the rigidbody 2D of the gameObject to manipulates its speed when coming out of the ground and I want it to just sticking out of the ground. How can I stop it when it reaches a certain tranform Y value.
Here is my code:
public float speed;
Rigidbody2D rb;
void Start () {
rb = GetComponent<Rigidbody2D>();
}
void Update () {
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
rb.AddForce(new Vector2(0, speed * Time.time), ForceMode2D.Impulse);
}
}
Certain transform value, or certain transform.position value?
I'll do it like this:
private float threshold = 10f;
private float startPosition = 0;
private RigidBody2D pikeRigidbody;:
private void Start()
{
startPosition = = this.transform.position;
pikeRigidbody = this.GetComponent<RigidBody2D>();
}
private void Update(){
if(this.transform.position.y >= (startPosition.y + threshold))
{
pikeRigidbody.velocity = Vector3.zero;
}
}
And attach the script to the pike object.
Edited to position.y instead of position

Trying to create a nice character controller?

I'm kind of new in the 2D environment of Unity.
I'm trying to create a platformer. For now, I have a simple map and my player.
My simple map and my player
My player have one script attached :
public class Player : MonoBehaviour
{
public float speed;
public float jump;
public GameObject raycastPoint; // Positioned at 0.01 pixel below the player
private SpriteRenderer spriteRenderer;
private Rigidbody2D body; // Gravity Scale of the Rigidbody2D = 50
private Animator animator;
private void Start()
{
spriteRenderer = GetComponent<SpriteRenderer>();
body = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
}
private void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
if (horizontal == 1 && spriteRenderer.flipX)
{
spriteRenderer.flipX = false;
}
else if (horizontal == -1 && !spriteRenderer.flipX)
{
spriteRenderer.flipX = true;
}
body.velocity = new Vector2(horizontal * speed, body.velocity.y);
animator.SetFloat("Speed", Mathf.Abs(horizontal));
float vertical = Input.GetAxisRaw("Vertical");
if (vertical == 1)
{
RaycastHit2D hit = Physics2D.Raycast(raycastPoint.transform.position, Vector2.down, 0.01f);
if (hit.collider != null)
{
body.AddForce(new Vector2(0f, jump));
}
}
}
}
For now I have achieved the right and left movements.
For the jump, I have a child gameobject just under the player and I'm firing a raycast to the bottom so I can know if my player is grounded or not.
I have two problems.
PROBLEM NUMBER ONE.
Sometimes I feel like my "AddForce" line is executed multiple times my player is jumping really high
Problem number one image
PROBLEM NUMBER TWO.
When I'm jumping to the left or right wall, if I keep pressing the left or right key my player is not falling anymore and stay against the wall.
Problem number two image
I tried to put my code into the FixedUpdate method (I know it's better) but I had the same results.
And I tried to set the Collision Detection on Continuous but I had the same results.
Try this code for your first problem :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(BoxCollider2D))]
[RequireComponent(typeof(Rigidbody2D))]
[RequireComponent(typeof(Animator))]
public class Player_Controller : MonoBehaviour {
private Rigidbody2D body;
private bool canJump, facingRight;
private Animator anim;
[SerializeField]
private float moveSpeed, jumpForce;
void Start ()
{
SetStartValues();
}
void FixedUpdate ()
{
float horizontal = Input.GetAxis("Horizontal");
animator.SetFloat("Speed", Mathf.Abs(horizontal));
Flip(horizontal);
Move(horizontal);
Jump();
}
private void SetStartValues()
{
body = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
canJump = true;
facingRight = true;
}
private void Jump()
{
if (Input.GetKeyDown(KeyCode.Space) && canJump)
{
body.AddForce(new Vector2(0, jumpForce));
canJump = false;
}
}
private void Move(float x)
{
body.velocity = new Vector2(x * moveSpeed * Time.deltaTime, body.velocity.y);
}
private void Flip(float x)
{
if (x > 0 && !facingRight|| x < 0 && facingRight)
{
facingRight = !facingRight;
transform.localScale = new Vector2(transform.localScale.x * -1, transform.localScale.y) ;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Ground")
{
canJump = true;
}
}
}
And don't forget to put the "Ground" tag on your ground object.

Rigidbody is being dragged back to bouncy object

I have an object tagged "Bouncy object" that pushes my player on collision; it works but after collision, my player is like being dragged back to the object tagged "Bouncy object", then does the same thing again like a cycle. The code I used is:
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Bouncy object")
GetComponent<Rigidbody2D>().AddForce(transform.right * 38, ForceMode2D.Impulse);
}
I then set the drag on the player's Rigidbody to: 1.49. How would I stop this from happening? What I want is for the object tagged "Bouncy object" to push my player on collision (trigger) then freeze Rigidbody2D for like 2 seconds, then allows me to control my player.
Here is the code you want. I tested just now.
If Cube collide with Block, it bounce to back 0.1 sec and freeze 1 sec.
The key is '-GetComponent ().velocity'.
Here is the screenshot of editor.
public class PlayerController : MonoBehaviour {
public float force = 10f;
float speed = 5f;
float freezeTime = 1f;
bool isCollide = false;
void FixedUpdate ()
{
float dirX = Input.GetAxis ("Horizontal");
float dirY = Input.GetAxis ("Vertical");
Vector3 movement = new Vector2 (dirX, dirY);
if(isCollide==false)
GetComponent<Rigidbody2D> ().velocity = movement * speed;
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Boundary") {
isCollide = true;
GetComponent<Rigidbody2D> ().AddForce (-GetComponent<Rigidbody2D> ().velocity * force, ForceMode2D.Impulse);
Invoke("StartFreeze", 0.1f);
}
}
void StartFreeze()
{
GetComponent<Rigidbody2D> ().constraints = RigidbodyConstraints2D.FreezeAll;
Invoke("ExitFreeze", freezeTime);
}
void ExitFreeze()
{
GetComponent<Rigidbody2D> ().constraints = RigidbodyConstraints2D.None;
isCollide = false;
}
}