OnPointerEnter and OnPointerExit not being triggered Unity - c#

Alright so basically the issue that I've been having is that for some reason a GameObject is interfering with the OnPointerEnter function. I'm pretty sure that OnPointerEnter detects only UI. So that's why I'm extremely confused when seeing that a specific GameObject in this case the PlayerLogic GameObject (which you can see in the screenshot) is for some reason interfering with the detection of UI elements. The reason I believe it is this specific GameObject is because once I do PlayerLogic.SetActive(false); OnPointerEnter starts to work again, and I'm also sure that it isn't any of the children of PlayerLogic because I've tried turning them off specifically and it still didn't work.
Inspector of the PlayerLogic object
Hierarchy
The code I'm using to test OnPointerEnter
After some testing I've realized that its the specific issue lies within the Player script on the PlayerLogic GameObject. Now what confuses me is that once I turn off the Player component OnPointer doesn't work, but if I were to remove the Player component completely from the PlayerLogic GameObject OnPointerEnter works.
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System.Collections;
using System.Collections.Generic;
public class Player : MonoBehaviour, TakeDamage {
[SerializeField] private Animator playerAnimator;
[SerializeField] private Transform mainCameraTransform;
private bool isRunning = false;
[SerializeField] private CharacterController controller;
public float speed = 10f;
[SerializeField] private float jumpForce = 3f;
[SerializeField] private float gravity = -10000.81f;
Vector3 velocity;
Vector3 desiredMoveDirection;
private float dashSpeed = 30f;
private float mouseX;
private float mouseY;
[SerializeField]
private Transform Target;
[SerializeField]
private Transform player;
private float turnSmoothVelocity;
private float time = 0f;
public bool playerIsAttacking = false;
[SerializeField] private Slider playerHealth, playerMana;
[SerializeField] private TextMeshProUGUI healthText, manaText;
private Vector3 originalSpawnPos;
private bool playerIsDead = false;
[SerializeField] private LayerMask enemyLayerMask;
[SerializeField] private Transform playerLook;
private ShowHPBar obj;
private bool HPBarShown = false;
private bool unshowingHPBar = false;
public bool lookingAtEnemy = false;
public RaycastHit hit;
[SerializeField] private Canvas abilityCanvas;
[SerializeField] private Slider CD1;
[SerializeField] private Slider CD2;
[SerializeField] private Slider CD3;
public List<Ability> currentlyEquippedAbilites = new List<Ability>();
public List<string> abilityTexts = new List<string>();
public float[] abilityCooldowns = new float[3];
private float manaRegenTime;
//public List<Image> abilityImages = new List<Image>();
private void Awake() {
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
private void Start() {
playerHealth.onValueChanged.AddListener(delegate {OnValueChangedHealth(); });
playerMana.onValueChanged.AddListener(delegate {OnValueChangedMana(); });
originalSpawnPos = transform.position;
}
private void Update() {
if (!playerIsDead) {
PlayerMovementAndRotation();
}
PlayerDash();
PlayerRun();
PlayerSeeEnemyHealth();
PlayerActivateAbility();
if (manaRegenTime > 0.5f) {
playerMana.value += playerMana.maxValue/100;
manaRegenTime = 0;
}
playerLook.rotation = mainCameraTransform.rotation;
time += Time.deltaTime;
manaRegenTime += Time.deltaTime;
#region Ability Cooldowns
if (currentlyEquippedAbilites.Count > 0) {
if (currentlyEquippedAbilites[0].cooldown <= abilityCooldowns[0])
{
currentlyEquippedAbilites[0].isOnCooldown = false;
abilityCooldowns[0] = 0;
CD1.value = 0;
}
else if (currentlyEquippedAbilites[0].isOnCooldown) {
abilityCooldowns[0] += Time.deltaTime;
CD1.value = currentlyEquippedAbilites[0].cooldown - abilityCooldowns[0];
}
}
if (currentlyEquippedAbilites.Count > 1) {
if (currentlyEquippedAbilites[1].cooldown <= abilityCooldowns[1])
{
currentlyEquippedAbilites[1].isOnCooldown = false;
abilityCooldowns[1] = 0;
CD2.value = 0;
}
else if (currentlyEquippedAbilites[1].isOnCooldown) {
abilityCooldowns[1] += Time.deltaTime;
CD2.value = currentlyEquippedAbilites[1].cooldown - abilityCooldowns[1];
}
}
if (currentlyEquippedAbilites.Count > 2) {
if (currentlyEquippedAbilites[2].cooldown <= abilityCooldowns[2])
{
currentlyEquippedAbilites[2].isOnCooldown = false;
abilityCooldowns[2] = 0;
CD3.value = 0;
}
else if (currentlyEquippedAbilites[2].isOnCooldown) {
abilityCooldowns[2] += Time.deltaTime;
CD3.value = currentlyEquippedAbilites[2].cooldown - abilityCooldowns[2];
}
}
#endregion
}
private void PlayerRun() {
if (Input.GetKey(KeybindsScript.RunKey) && (Input.GetAxisRaw("Horizontal") != 0 || Input.GetAxisRaw("Vertical") != 0)) {
playerAnimator.SetInteger("isRunning", 1);
playerAnimator.SetInteger("isIdle", 0);
playerAnimator.SetInteger("isWalking", 0);
speed = 15f;
}
else if (Input.GetAxisRaw("Horizontal") != 0 || Input.GetAxisRaw("Vertical") != 0) {
playerAnimator.SetInteger("isWalking", 1);
playerAnimator.SetInteger("isIdle", 0);
playerAnimator.SetInteger("isRunning", 0);
speed = 10f;
}
else {
playerAnimator.SetInteger("isRunning", 0);
playerAnimator.SetInteger("isWalking", 0);
playerAnimator.SetInteger("isIdle", 1);
speed = 10f;
}
}
private void PlayerMovementAndRotation() {
bool isGrounded = controller.isGrounded;
if (isGrounded && velocity.y < 0) {
velocity.y = -2f;
}
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 moveDir = (transform.right*horizontal+transform.forward*vertical).normalized;
controller.Move(moveDir*Time.deltaTime*speed);
transform.eulerAngles = new Vector3(0f, mainCameraTransform.eulerAngles.y, 0f);
if (Input.GetKeyDown(KeybindsScript.JumpKey) && isGrounded) {
velocity.y = Mathf.Sqrt(jumpForce * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
private void PlayerDash() {
if (Input.GetKeyDown(KeybindsScript.DashKeybind) && isRunning == false) {
if (Input.GetKey(KeybindsScript.MovementKeyBackward)) {
StartCoroutine(PlayerDashTiming(2));
}
else if (Input.GetKey(KeybindsScript.MovementKeyRight)) {
StartCoroutine(PlayerDashTiming(3));
}
else if (Input.GetKey(KeybindsScript.MovementKeyLeft)) {
StartCoroutine(PlayerDashTiming(4));
}
else {
StartCoroutine(PlayerDashTiming(1));
}
}
}
private void PlayerSeeEnemyHealth() {
if (Physics.Raycast(playerLook.position, playerLook.forward, out hit, 1000f, enemyLayerMask)) {
obj = hit.transform.gameObject.GetComponent<ShowHPBar>();
if (obj != null && !HPBarShown && !unshowingHPBar) {obj.ShowHPBarFunction(); HPBarShown = true;}
lookingAtEnemy = true;
}
else {
if (obj != null && HPBarShown) {StartCoroutine(UnShowHPBar(obj)); HPBarShown = false;}
}
}
public void PlayerEquipAbility(Ability ability, int place) {
if (currentlyEquippedAbilites.Count < place) {currentlyEquippedAbilites.Add(ability);}
else {currentlyEquippedAbilites[place-1] = ability;}
//if (abilityImages.Count < place) {abilityImages.Add(ability.icon);}
//else {abilityImages.Add(ability.icon);}
if (abilityTexts.Count < place) {abilityTexts.Add(ability.name);}
else {abilityTexts[place-1] = ability.name;}
for (int i=0;i < abilityTexts.Count;++i) {
abilityCanvas.transform.GetChild(i).GetChild(0).GetComponent<TextMeshProUGUI>().text = abilityTexts[i];
abilityCanvas.transform.GetChild(i).GetChild(1).GetComponent<Slider>().maxValue = ability.cooldown;
}
}
private void PlayerActivateAbility() {
if (Input.GetKeyDown(KeyCode.Alpha1)) {
if (currentlyEquippedAbilites[0] != null) {
if (currentlyEquippedAbilites[0].manaCost <= playerMana.value && !currentlyEquippedAbilites[0].isOnCooldown) {
ParticleEffect pe = currentlyEquippedAbilites[0].script.gameObject.GetComponent<ParticleEffect>();
playerMana.value -= currentlyEquippedAbilites[0].manaCost;
currentlyEquippedAbilites[0].isOnCooldown = true;
if (pe != null) {pe.PlayAnimation();}
}
}
}
}
public void OnValueChangedHealth() {
healthText.text = playerHealth.value + "/" + PlayerStats.HealthPoints;
}
public void OnValueChangedMana() {
manaText.text = playerMana.value + "/" + PlayerStats.ManaAmount;
}
public void TakeDamageFunction(float damage) {
playerHealth.value -= damage;
if (playerHealth.value <= 0) {
StartCoroutine(PlayerDeath());
}
}
IEnumerator PlayerDashTiming(int x) {
isRunning = true;
float time = 0f;
Vector3 savedVector = Vector3.zero;
switch (x) {
case 1:
savedVector = transform.forward;
break;
case 2:
savedVector = -transform.forward;
break;
case 3:
savedVector = transform.right;
break;
case 4:
savedVector = -transform.right;
break;
}
while(time < .3f)
{
time += Time.deltaTime;
controller.Move(savedVector * dashSpeed * Time.deltaTime);
yield return null;
}
yield return new WaitForSeconds(1.5f);
isRunning = false;
}
IEnumerator PlayerDeath() {
//Respawn
playerIsDead = true;
playerAnimator.enabled = false;
yield return new WaitForSeconds(1f);
playerHealth.value = 100;
transform.position = originalSpawnPos;
yield return new WaitForSeconds(0.1f);
playerIsDead = false;
playerAnimator.enabled = true;
}
IEnumerator UnShowHPBar(ShowHPBar obj) {
unshowingHPBar = true;
yield return new WaitForSeconds(1.5f);
obj.ShowHPBarFunction();
unshowingHPBar = false;
}
}
This is the Player.cs script.

I'm pretty sure that OnPointerEnter detects only UI.
No.
It works "out of the box" on UI because by default every Canvas contains a GraphicsRaycaster component which is then used and handled by the EventSystem.
For non-UI 3D objects you have to make sure
your objects have 3D Colliders
the Colliders are on the same object as the IPointerXY interfaces
on your Camera there is a PhysicsRayster component
For non-UI 2D objects quite similar
your objects have a 2D Collider
the colliders are on the same object as the IPointerXY interfaces
the Camera has a Physics2DRaycaster component
Note that it is possible that any other collider or in general raycast blocking object is between your input and the target object which would also prevent the OnPointerXY to be triggered on your objects.
The CharacterController
is simply a capsule shaped Collider
which can be told to move in some direction from a script.
which is probably blocking the input.
Now with your Player code:
You do
Cursor.lockState = CursorLockMode.Locked;
in Awake so even if you turn it off afterwards this already took effect.

Related

C# Unity 2D Platformer | Character controller walks in air after double jump and hit enemy in air

I have a 2D character controller and part of the controller is the ability to double jump, but if my player hits en enemy when in air after a double jump or down slash attack the player starts walking in a straight line in the air, im assuming im missing a ground check for this but was wondering if I could have any assistance with this please:
CS code is:
public class PlayerController : MonoBehaviour
{
[Header("Input")]
public float jumpHoldTime = 0.3f;
float horizontalInput;
float lastHorizontalInput;
bool dead = false;
[Header("Movement")]
public Animator anim;
public float moveSpeed = 5.0f;
float currentMove = 0f;
public bool facingRight = true;
private Rigidbody2D rb;
Vector2 finalMovement;
bool runMovement = false;
bool isMoving = false;
[Header("Vertical Movement")]
public int jumpCounter = 2;
public float jumpSpeed = 5f;
public bool inAir = true;
public bool canDoubleJump = false;
bool jumpHeld = false;
[Header("Gravity")]
public float upGravity = -16f;
public float downGravity = -20f;
public float jumpHoldGravity = -5f;
public float maxFallSpeed = -10f;
float currentGravity = 0f;
[Header("Col Handler")]
public bool wallRight = false;
public bool wallLeft = false;
Collider2D currentGround;
Collider2D leftWall;
Collider2D rightWall;
[Header("Attack")]
public Transform attackPointRight;
public Transform attackPointDown;
public float attackRange = 0.5f;
public int attackDamage = 1;
public float attackRate = 2f;
private float nextAttackCount = 0f;
private bool attackingForward = true;
public LayerMask enemyLayer;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if(dead)
{
return;
}
GetInput();
}
void GetInput()
{
horizontalInput = Input.GetAxis("Horizontal");
if(horizontalInput != 0 && lastHorizontalInput == 0) // move if input on current frame
{
isMoving = true;
anim.SetBool("Moving", true);
}
if(horizontalInput == 0 && lastHorizontalInput != 0) // stop when movement ends on frame
{
isMoving = false;
anim.SetBool("Moving", false);
}
if(horizontalInput > 0f && !facingRight || horizontalInput < 0f && facingRight)
{
dirFlip();
}
if(Input.GetButtonDown("Jump"))
{
Jump();
}
lastHorizontalInput = horizontalInput;
}
void dirFlip()
{
facingRight = !facingRight;
transform.Rotate(transform.up, 180f);
}
void Jump()
{
if(canDoubleJump)
{
jumpCounter -= 1;
}
if(jumpCounter < 0 || (inAir && !canDoubleJump))
{
return;
}
inAir = true;
anim.SetTrigger("Jump");
anim.SetBool("InAir", true);
currentGravity = jumpSpeed;
StartCoroutine(JumpHoldRoutine());
}
IEnumerator JumpHoldRoutine()
{
jumpHeld = true;
float timer = 0f;
while(timer < jumpHoldTime && Input.GetButton("Jump"))
{
timer += Time.deltaTime;
yield return null;
}
jumpHeld = false;
}
private void FixedUpdate()
{
if(inAir)
{
setMovement();
if(jumpHeld)
{
currentGravity += jumpHoldGravity * Time.deltaTime;
}
else
{
if(currentGravity > 0f)
{
currentGravity += upGravity * Time.deltaTime;
}
else if(currentGravity <= 0f)
{
currentGravity += downGravity * Time.deltaTime;
}
}
currentGravity = Mathf.Clamp(currentGravity, maxFallSpeed, jumpSpeed);
finalMovement.y = currentGravity;
}
if(isMoving)
{
setMovement();
currentMove = horizontalInput * moveSpeed;
if(currentMove > 0f && wallRight || currentMove < 0f && wallLeft || wallRight)
{
currentMove = 0f;
}
finalMovement.x = currentMove;
}
if(runMovement)
{
rb.MovePosition((Vector2)transform.position + finalMovement * Time.deltaTime);
runMovement = false;
}
}
void setMovement()
{
if(!runMovement)
{
runMovement = true;
finalMovement = Vector2.zero;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
ColliderDistance2D collDist = collision.collider.Distance(GetComponent<Collider2D>());
Debug.DrawRay(collDist.pointA, collDist.normal, Color.black, 1f);
if(collision.collider.tag == "Enviro")
{
if(collDist.normal.y > 0.1f) // On ground to reset double jump
{
jumpCounter = 2;
}
if(collDist.normal.y > 0.1f) // Ground check
{
Ground(collision.collider);
}
if(collDist.normal.y < -0.1f) // ceiling
{
currentGravity = 0f;
jumpHeld = false;
}
if(collDist.normal.x < -0.9f) // right wall
{
wallRight = true;
rightWall = collision.collider;
}
if(collDist.normal.x > 0.9f)
{
wallLeft = true;
leftWall = collision.collider;
}
}
else if(collision.collider.tag == "Rat")
{
inAir = false;
Jump();
GetComponent<Health>().TakeDamage(1);
}
else if(collision.collider.tag == "Ghost")
{
inAir = false;
Jump();
GetComponent<Health>().TakeDamage(1);
}
else if(collision.collider.tag == "LavaB")
{
inAir = false;
Jump();
GetComponent<Health>().TakeDamage(1);
}
else if(collision.collider.tag == "BouncySpikeBall")
{
inAir = false;
Jump();
}
else if(collision.collider.tag == "Skeleton")
{
inAir = false;
Jump();
GetComponent<Health>().TakeDamage(1);
}
}
void Ground(Collider2D newGround)
{
inAir = false;
currentGravity = 0f;
currentGround = newGround;
anim.SetBool("InAir", false);
}
private void OnCollisionExit2D(Collision2D collision) // no longer collidiing with object
{
if(collision.collider.tag == "Enviro")
{
if(collision.collider == currentGround)
{
if(!inAir)
{
inAir = true;
currentGround = null;
anim.SetTrigger("Jump");
anim.SetBool("InAir", true);
}
}
if(collision.collider == rightWall)
{
rightWall = null;
wallRight = false;
}
if(collision.collider == leftWall)
{
leftWall = null;
wallLeft = false;
}
}
}
}
I'm sorry that this is kinda long, I cut out parts that were about the attacking or something irrelevant to try and limit how much was here.
Basically, if I double jump and then hit/down hit or touch an enemy while I'm still up in the air my player freezes in that axis and can only move left and right but the animations still work fine.
Little bit puzzled about this and need some assistance please, also let me know if Im not giving enough information about the problem :)
I've tried to toggle the inAir bool after the hit but it doesn't seem to help with the issue. I expect the player to just fall down again instead of staying still and moving in the air
you can make your player be pushed up by rb.addforce with a small amount of force when he hits an enemy, then the jump checker which is jumpheld or jump counter will be resit.

player collision does not work with objects

I'm making an endless runner game and i have a question about my player colliding with so,e obstacles, I used Raycast but when i try to debug this collision doesn't occur.
Here my player Code.
public class Player : MonoBehaviour
{
private CharacterController controller;
public float speed;
public float jumpHeight;
private float jumpVelocity;
public float gravity;
public float rayRadius;
public LayerMask layer;
public float horizontalSpeed;
private bool isMovingLeft;
private bool isMovingRight;
private bool isDead;
// Start is called before the first frame update
void Start()
{
controller = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
Vector3 direction = Vector3.forward * speed;
if(controller.isGrounded)
{
if(Input.GetKeyDown(KeyCode.Space))
{
jumpVelocity = jumpHeight;
}
if(Input.GetKeyDown(KeyCode.RightArrow)&& transform.position.x < 3.58f && !isMovingRight)
{
isMovingRight = true;
StartCoroutine(RightMove());
}
if(Input.GetKeyDown(KeyCode.LeftArrow)&& transform.position.x > -3.58f && !isMovingLeft)
{
isMovingLeft = true;
StartCoroutine(LeftMove());
}
}
else
{
jumpVelocity -= gravity;
}
OnCollision();
direction.y = jumpVelocity;
controller.Move(direction * Time.deltaTime);
}
IEnumerator LeftMove()
{
for(float i = 0; i < 10; i += 0.1f)
{
controller.Move(Vector3.left * Time.deltaTime * horizontalSpeed);
yield return null;
}
isMovingLeft = false;
}
IEnumerator RightMove()
{
for (float i = 0; i < 10; i += 0.1f)
{
controller.Move(Vector3.right * Time.deltaTime * horizontalSpeed);
yield return null;
}
isMovingRight = false;
}
void OnCollision()
//The player will collide with obstacles that have a specific type of layer and dead.
{
RaycastHit hit;
if(Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, rayRadius, layer) && !isDead)
{
Debug.Log("GameOver!");
speed = 0;
jumpHeight = 0;
isDead = true;
}
}
}
Instead of using raycast inside OnCollision function. You can do this with very much by following these steps:
Add a tag to your obstacles let say its "Obstacle"
Add collider to them
Check when you collide with someone that if it is obstacle or not if yes then you can call your dead function.
void OnCollisionEnter(Collision collision)
{
if(collision.transform.CompareTag("Obstacle")){
Debug.Log("GameOver!");
speed = 0;
jumpHeight = 0;
isDead = true;
}
}
In this way you can detect collision with super ease instead of using raycast.

swipe controls in my script not working as intended in c# unity3d

This code works for like 2min and stops taking swipe input, i need to relaunch the editor then again it works for 2min. if i did same with keyboard input it works just fine. there is a problem in swipemanager ill put both code................................................................................................................................................................................................
using UnityEngine;
public class SwipeManager : MonoBehaviour
{
public static bool tap, swipeLeft, swipeRight, swipeUp, swipeDown;
private bool isDraging = false;
private Vector2 startTouch, swipeDelta;
private void Update()
{
tap = swipeDown = swipeUp = swipeLeft = swipeRight = false;
#region Standalone Inputs
if (Input.GetMouseButtonDown(0))
{
tap = true;
isDraging = true;
startTouch = Input.mousePosition;
}
else if (Input.GetMouseButtonUp(0))
{
isDraging = false;
Reset();
}
#endregion
#region Mobile Input
if (Input.touches.Length > 0)
{
if (Input.touches[0].phase == TouchPhase.Began)
{
tap = true;
isDraging = true;
startTouch = Input.touches[0].position;
}
else if (Input.touches[0].phase == TouchPhase.Ended || Input.touches[0].phase == TouchPhase.Canceled)
{
isDraging = false;
Reset();
}
}
#endregion
//Calculate the distance
swipeDelta = Vector2.zero;
if (isDraging)
{
if (Input.touches.Length < 0)
swipeDelta = Input.touches[0].position - startTouch;
else if (Input.GetMouseButton(0))
swipeDelta = (Vector2)Input.mousePosition - startTouch;
}
//Did we cross the distance?
if (swipeDelta.magnitude > 100)
{
//Which direction?
float x = swipeDelta.x;
float y = swipeDelta.y;
if (Mathf.Abs(x) > Mathf.Abs(y))
{
//Left or Right
if (x < 0)
swipeLeft = true;
else
swipeRight = true;
}
else
{
//Up or Down
if (y < 0)
swipeDown = true;
else
swipeUp = true;
}
Reset();
}
}
private void Reset()
{
startTouch = swipeDelta = Vector2.zero;
isDraging = false;
}}
This is code of playermanager
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerController : MonoBehaviour
{
public static bool tap, swipeLeft, swipeRight, swipeUp, swipeDown;
private bool isDraging = false;
private Vector2 startTouch, swipeDelta;
// Start is called before the first frame update
private CharacterController controller;
private Vector3 direction;
public float forwardSpeed;
private int desiredLane = 1;//1=left 2=middle 3=right
public float laneDistance;
public float Jumpforce;
public float Gravity = -20;
public GameObject GameOver;
public float MaxSpeed;
public Animator animator;
public SwipeManager sm;
void Start()
{
controller = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
if(!PlayerManager.isGameStarted)
return;
animator.SetBool("isGameStarted", true);
if(forwardSpeed<MaxSpeed)
forwardSpeed += 0.05f* Time.deltaTime;
direction.z = forwardSpeed;
animator.SetBool("IsGrounded", controller.isGrounded);
if (controller.isGrounded)
{
direction.y = -1;
if (SwipeManager.swipeUp)
{
Jump();
}
}
else { direction.y += Gravity * Time.deltaTime; }
if (SwipeManager.swipeDown)
{
StartCoroutine(slide());
}
if (SwipeManager.swipeRight)
{
desiredLane++;
if (desiredLane == 3)
desiredLane = 2;
}
if (SwipeManager.swipeLeft)
{
desiredLane--;
if (desiredLane == -1)
desiredLane = 0;
}
Vector3 targetPosition = transform.position.z * transform.forward + transform.position.y * transform.up;
if (desiredLane == 0)
{
targetPosition += Vector3.left * laneDistance;
}
else if (desiredLane == 2)
{
targetPosition += Vector3.right * laneDistance;
}
transform.position = targetPosition;
}
private void FixedUpdate()
{
if(!PlayerManager.isGameStarted)
return;
controller.Move(direction * Time.fixedDeltaTime);
}
public void Jump()
{
direction.y = Jumpforce;
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
if (hit.transform.tag == "Obstacle")
{
GameOver.SetActive(true);
Time.timeScale = 0;
}
}
private IEnumerator slide()
{
controller.center = new Vector3(0,-0.5f,0);
controller.height = 1;
animator.SetBool("isCrouching", true);
yield return new WaitForSeconds(1.3f);
controller.center = new Vector3(0,0,0);
animator.SetBool("isCrouching", false);
controller.height = 2;
}}
I think your swipeDelta = Vector2.zero; should be called in the Start() function and your Reset() function only, as in the Update() it is getting zero every frame.

I'm trying to write a program for my character to jump. It is coming up with errors. I'm not quite sure how to fix them

I'm trying to make my game. I have a character and I'm trying to get it to jump. I can make the character walk, idle and slide but it won't jump. I'm doing all the coding in 1 script. I'm getting the attached error messages but not sure how to fix them. I've tried a number of things but can't get any of it to work.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
public class Player : MonoBehaviour
{
private Rigidbody2D myRigidbody;
private Animator myAnimator;
[SerializeField]
private float movementSpeed;
private bool walk;
private bool slide;
private bool facingRight;
[SerializeField]
private Transform[] groundPoints;
[SerializeField]
private float groundRadius;
private LayerMask whatIsGround;
private bool IsGrounded;
private bool jump;
[SerializeField]
private bool airControl;
[SerializeField]
private float jumpForce;
// Start is called before the first frame update
void Start()
{
facingRight = true;
myRigidbody = GetComponent<Rigidbody2D>();
myAnimator = GetComponent<Animator>();
}
void Update()
{
HandleInput();
}
// Update is called once per frame
void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
isGround = IsGrounded();
HandleMovement(horizontal);
Flip(horizontal);
HandleWalk();
ResetValues();
}
private void HandleMovement(float horizontal)
{
if (!this.myAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Walk")&& (isGround || airControl))
{
myRigidbody.velocity = new Vector2(horizontal * movementSpeed, myRigidbody.velocity.y);
}
if (isGround && jump)
{
isGround = false;
myRigidbody.AddForce(new Vector2(0, jumpForce));
}
if (slide && !this.myAnimator.GetCurrentAnimatorStateInfo(0).IsName("Slide"))
{
myAnimator.SetBool("slide", true);
}
else if (!this.myAnimator.GetCurrentAnimatorStateInfo(0).IsName("slide"))
{
myAnimator.SetBool("slide", false);
}
myAnimator.SetFloat("speed", Mathf.Abs(horizontal));
}
private void HandleWalk()
{
if (walk)
{
myAnimator.SetTrigger("walk");
myRigidbody.velocity = Vector2.zero;
}
}
private void HandleInput()
{
if (Input.GetKeyDown(KeyCode.Space))
{
jump = true;
}
if (Input.GetKeyDown(KeyCode.LeftShift))
{
walk = true;
}
if (Input.GetKeyDown(KeyCode.LeftControl))
{
slide = true;
}
}
private void Flip(float horizontal)
{
if (horizontal > 0 && !facingRight || horizontal < 0 && facingRight)
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
private void ResetValues()
{
walk = false;
slide = false;
}
private bool isGround()
{
if (myRigidbody.velocity.y <= 0)
{
foreach (Transform point in instance.groundPoints)
{
Collider2D[] colliders = Physics2D.OverlapCircleAll (point.position, instance.groundRadius, instance.whatIsGround);
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject != gameObject)
{
return true;
}
}
}
}
return false;
}
}
Error messages for player to jump
Rename field private bool IsGrounded; to private bool isGround;
Also you need to change the method name private bool isGround() {} to private bool IsGrounded() {}
And remove instance from IsGrounded method.
private bool IsGrounded()
{
if (myRigidbody.velocity.y <= 0)
{
foreach (Transform point in groundPoints)
{
Collider2D[] colliders = Physics2D.OverlapCircleAll(point.position, groundRadius, whatisGround);
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject != gameObject)
{
return true;
}
}
}
}
return false;
}

Unity: My enemy projectile is being destroyed before ever leaving it's spawn location. What am i doing wrong?

Like the title says, the enemy projectiles are not launching. They are spawned and destroyed in the same place. They do not fire toward the target. Code in link:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MonkeyController : MonoBehaviour {
private const int MAX_INJURES = 1;
public float DurationMovement = 2f;
public Transform SpawnLocation;
public Transform[] PatrolPoints;
public GameObject MonkeyProjectile;
public Rigidbody2D Abby;
public float AttackDelay = 0.75f;
public float ProjectileSpeed = 1;
public int ProjectilesCount = 4;
public float activePosition;
public float passivePosition;
private List<GameObject> ProjectileList = new List<GameObject>();
private int PatrolIndex = 0;
private int injures = 0;
private bool canPatrol;
private Coroutine fireCoroutine;
private Coroutine patrolCoroutine;
private Coroutine movementCoroutine;
WaitForSeconds delay;
Vector2 AttackVector = Vector2.zero;
// Use this for initialization
private void Start () {
delay = new WaitForSeconds(AttackDelay);
InitializeProjectileList();
fireCoroutine = StartCoroutine(MonkeyFireProjectileBehaviour());
patrolCoroutine = StartCoroutine(PatrolBehaviour(PatrolPoints[PatrolIndex].position));
}
private IEnumerator MonkeyFireProjectileBehaviour()
{
yield return delay;
if (GameManager.GetInstance().gameState == GameState.GAME_OVER)
yield return null;
AttackVector = Abby.transform.position - (transform.position /*+ (Vector3)Abby.velocity/10f*/);
FireProjectile(AttackVector);
fireCoroutine = StartCoroutine(MonkeyFireProjectileBehaviour());
}
private IEnumerator PatrolBehaviour(Vector3 animationLocation)
{
canPatrol = true;
float distance = (transform.position - animationLocation).magnitude;
float duration = DurationMovement;
Vector3 startingPos = transform.position;
float t = 0;
while (t < 1 && canPatrol)
{
t += Time.deltaTime / duration;
transform.position = Vector3.Lerp(startingPos, animationLocation, t);
yield return null;
}
if (!canPatrol)
yield break;
transform.position = animationLocation;
IncrementMovementIndex();
patrolCoroutine = StartCoroutine(PatrolBehaviour(PatrolPoints[PatrolIndex].position));
yield return null;
}
private void IncrementMovementIndex()
{
PatrolIndex++;
if(PatrolIndex == PatrolPoints.Length)
{
PatrolIndex = 0;
}
}
private void InitializeProjectileList()
{
GameObject Projectile;
for (int i = 0; i < ProjectilesCount; i++)
{
Projectile = Instantiate(MonkeyProjectile);
Projectile.SetActive(false);
ProjectileList.Add(Projectile);
}
}
private void FireProjectile(Vector2 forceProjectile)
{
foreach (GameObject projectile in ProjectileList)
{
if (!projectile.activeInHierarchy)
{
projectile.transform.position = SpawnLocation.position;
projectile.SetActive(true);
projectile.GetComponent<TrailRenderer>().enabled = true;
projectile.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic;
projectile.GetComponent<Rigidbody2D>().AddForce(forceProjectile * (ProjectileSpeed + Random.Range(0, ProjectileSpeed/2)), ForceMode2D.Impulse);
break;
}
}
}
private IEnumerator DoMovementCoroutine()
{
yield return new WaitForSeconds (0.01F);
transform.localPosition = new Vector2(passivePosition, 0);
yield return AnimatorExecutive.AnimatePositionCoroutine (gameObject, new Vector2 (activePosition, 0), 5.0F);
fireCoroutine = StartCoroutine(MonkeyFireProjectileBehaviour());
patrolCoroutine = StartCoroutine(PatrolBehaviour(PatrolPoints[PatrolIndex].position));
}
private void OnCollisionEnter2D(Collision2D otherCollision)
{
if (otherCollision.gameObject.tag == "Projectile")
{
injures++;
if (injures >= MAX_INJURES)
{
injures = 0;
canPatrol = false;
GetComponent<AudioSource>().Play();
if(fireCoroutine != null) StopCoroutine (fireCoroutine);
if(patrolCoroutine != null) StopCoroutine (patrolCoroutine);
movementCoroutine = StartCoroutine (DoMovementCoroutine());
}
}
}
}
With the information your provided, I would say the problem you may be facing is the GameObject you pass in the inspector to get the SpawnLocation has got a collider and a script with a OnCollisionEnter2D, which detect the projectil when you instantiate it and destroy it.
However, you are not destroying the projectil inside this OnCollisionEnter2D.
private void OnCollisionEnter2D(Collision2D otherCollision)
{
if (otherCollision.gameObject.tag == "Projectile")
{
injures++;
if (injures >= MAX_INJURES)
{
injures = 0;
canPatrol = false;
GetComponent<AudioSource>().Play();
if(fireCoroutine != null) StopCoroutine (fireCoroutine);
if(patrolCoroutine != null) StopCoroutine (patrolCoroutine);
movementCoroutine = StartCoroutine (DoMovementCoroutine());
}
}
}
In the case you dont have in your code any line to destroy the projectil gameobject after a collision. The problem could be you are not reaching this line projectile.SetActive(true);
I will try to replicate your code and check what may be happening

Categories