I'm try to make Basketball hoops, I can throw ball one time, I reset game but I can not throw ball again , I don't like to reset scene.
GameController is a empty object [Manager] and below script attach to it.
GameController.cs:
public PlayerArcade player;
public float restartTime = 5f;
public static bool ResetBall = false;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
if(player.HoldingBall == false)
{
restartTime -= Time.deltaTime;
if (restartTime <= 0)
{
//SceneManager.LoadScene("Intro");
ResetBall = true;
restartTime = 5f;
}
// ResetBall = true;
}
}
My main player script as PlayerArcade.cs:
public GameObject Ball;
public Ball ball;
Rigidbody ballrb;
public GameObject PlayerCamera;
public float BallDistance = 1f;
public float ThrowPowerStrong = 550f;
public float ThrowPowerWeak = 350f;
public bool HoldingBall = true;
void Start()
{
ballrb = Ball.GetComponent<Rigidbody>();
ballrb.useGravity = false;
}
private void Awake()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
if (GameController.ResetBall == true)
{
ballrb.constraints = RigidbodyConstraints.None;
Ball.transform.position = new Vector3(212.5f, 3.227f, 4.11f);
ballrb.velocity = Vector3.zero;
ballrb.angularVelocity = Vector3.zero;
ballrb.transform.eulerAngles = new Vector3(0f, 0f, 0f);
ballrb.useGravity = false;
HoldingBall = true;
}
if (HoldingBall)
{
Ball.transform.position = PlayerCamera.transform.position + PlayerCamera.transform.forward * BallDistance;
if (Input.GetKeyDown(KeyCode.Y))
{
Debug.Log(ThrowPowerStrong);
HoldingBall = false;
ballrb.useGravity = true;
ballrb.AddForce(PlayerCamera.transform.forward * ThrowPowerStrong);
}
if (Input.GetKeyUp(KeyCode.A))
{
HoldingBall = false;
ballrb.useGravity = true;
ballrb.AddForce(PlayerCamera.transform.forward * ThrowPowerWeak);
}
}
}
And Ball.cs is attached to my ball object:
public PlayerArcade player;
[SerializeField] Transform PlayerBall;
Rigidbody ballrb;
// Start is called before the first frame update
void Start()
{
ballrb = PlayerBall.GetComponent<Rigidbody>();
}
private void Awake()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
when you throw the ball by pressing (A, or Y) just do
GameController.ResetBall = false; GameController.ResetBall = false;
Related
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.
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.
I am trying to make a function named "Attack()" that will ocurr diferently if the player is facing a diferent direction in Unity 2D but i am getting the error that i have stated above. I am also getting this error "'Attack' does not exist in the current context" . I am fairly new to Unity so please have patience. Here is the code
` public class PlayerCombat : MonoBehaviour {
public Transform AttackAreaRight;
public float AttackRangeRight = 0.5f;
public float AttackRangeLeft = 0.5f;
public Transform AttackAreaLeft;
public bool IsFacingRight = true;
public bool IsFacingLeft = false;
public LayerMask EnemyLayers;
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
IsFacingRight = false;
IsFacingLeft = true;
Debug.Log("FacingLeft");
}
if (Input.GetKeyDown(KeyCode.D))
{
IsFacingLeft = false;
IsFacingRight = true;
Debug.Log("FacingRight");
}
if (Input.GetKeyDown(KeyCode.F))
{
Attack();
}
if (IsFacingRight = true) ;
{
void Attack()
{
Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(AttackAreaRight.position, AttackRangeRight, EnemyLayers);
foreach (Collider2D enemy in hitEnemies)
{
Debug.Log("LMAORight");
}
}
}
if (IsFacingLeft = true) ;
{
void Attack();
{
Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(AttackAreaLeft.position, AttackRangeLeft, EnemyLayers);
foreach (Collider2D enemy in hitEnemies)
{
Debug.Log("LMAOLeft");
}
}
}
}
}
`
So there's a few issues here. This is more what you want.
public Transform AttackAreaRight;
public float AttackRangeRight = 0.5f;
public float AttackRangeLeft = 0.5f;
public Transform AttackAreaLeft;
public bool IsFacingRight = true;
public LayerMask EnemyLayers;
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
IsFacingRight = false;
Debug.Log("FacingLeft");
}
if (Input.GetKeyDown(KeyCode.D))
{
IsFacingRight = false;
Debug.Log("FacingRight");
}
if (Input.GetKeyDown(KeyCode.F))
{
Attack();
}
}
void Attack()
{
Vector2 attackPosition;
float attackRange;
if (IsFacingRight)
{
attackPosition = AttackAreaRight.position;
attackRange = AttackRangeRight;
}
else
{
attackPosition = AttackAreaLeft.position;
attackRange = AttackRangeLeft;
}
Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attackPosition, attackRange, EnemyLayers);
foreach (Collider2D enemy in hitEnemies)
{
Debug.Log("Attacked");
}
}
So the first problem is you declared a function inside a function. Update() is a unity function called every frame so inside of it you can't have a function declared (that what you were doing with void Attack()).
Now if you want to set a value for your character's direction (left/right) its easier to only have 1 boolean so you don't have errors later on like IsLeft bieng true and IsRight being true. Since if IsRight is true than IsLeft must be false and so on.
You can then check this boolean inside the attack function and set the corresponding data for the OverlapCircle.
I'm not sure it is working or not but at least now not giving error on compilation.
If you could test it.
using UnityEngine;
public class PlayerCombat : MonoBehaviour
{
public Transform AttackAreaRight;
public float AttackRangeRight = 0.5f;
public float AttackRangeLeft = 0.5f;
public Transform AttackAreaLeft;
public bool IsFacingRight = true;
public bool IsFacingLeft = false;
public LayerMask EnemyLayers;
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
IsFacingRight = false;
IsFacingLeft = true;
Debug.Log("FacingLeft");
}
if (Input.GetKeyDown(KeyCode.D))
{
IsFacingLeft = false;
IsFacingRight = true;
Debug.Log("FacingRight");
}
if (Input.GetKeyDown(KeyCode.F)){
Attack();
}
}
private void Attack()
{
if (IsFacingLeft == true && IsFacingRight == false)
{
Collider2D[] hitEnemies =
Physics2D.OverlapCircleAll(AttackAreaLeft.position, AttackRangeLeft, EnemyLayers);
foreach (Collider2D enemy in hitEnemies)
{
Debug.Log("LMAOLeft");
}
}
else if (IsFacingRight == true && IsFacingLeft == false)
{
Collider2D[] hitEnemies =
Physics2D.OverlapCircleAll(AttackAreaRight.position, AttackRangeRight, EnemyLayers);
foreach (Collider2D enemy in hitEnemies)
{
Debug.Log("LMAORight");
}
}
}
}
I found a code that works great in my game to pick up an object and throw it but when two objects are next to each other, the game picks both of them at the same time because it is calculated from player's distance to the object.
I tried to understand rays but I can't sort it out...
Here is the code:
using UnityEngine;
using System.Collections;
public class ThrowObject : MonoBehaviour
{
public Transform player;
public Transform playerCam;
public float throwForce = 10;
bool hasPlayer = false;
bool beingCarried = false;
public AudioClip[] soundToPlay;
private AudioSource audio;
public int dmg;
private bool touched = false;
void Start()
{
audio = GetComponent<AudioSource>();
}
void Update()
{
float dist = Vector3.Distance(gameObject.transform.position, Input.mousePosition);
if (dist <= 2.5f)
{
hasPlayer = true;
}
else
{
hasPlayer = false;
}
if (hasPlayer && Input.GetButtonDown("Use"))
{
GetComponent<Rigidbody>().isKinematic = true;
transform.parent = playerCam;
beingCarried = true;
}
if (beingCarried)
{
if (touched)
{
GetComponent<Rigidbody>().isKinematic = false;
transform.parent = null;
beingCarried = false;
touched = false;
}
if (Input.GetMouseButtonDown(0))
{
GetComponent<Rigidbody>().isKinematic = false;
transform.parent = null;
beingCarried = false;
GetComponent<Rigidbody>().AddForce(playerCam.forward * throwForce);
RandomAudio();
}
else if (Input.GetMouseButtonDown(1))
{
GetComponent<Rigidbody>().isKinematic = false;
transform.parent = null;
beingCarried = false;
}
}
}
void RandomAudio()
{
if (audio.isPlaying){
return;
}
audio.clip = soundToPlay[Random.Range(0, soundToPlay.Length)];
audio.Play();
}
void OnTriggerEnter()
{
if (beingCarried)
{
touched = true;
}
}
}
Any help would be gladly appreciated. Thank you in advance!
Have a look at OnMouseOver and OnMouseEnter functions
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseOver.html
I know that this is a fairly regular question however having tried the solutions provided I have not been having much luck. Trying to get some object to collide in unity which worked, however the OnCollision2d call is not being made after they collide. Hoping to get some help on why this is happening.
The two classes provided here
[RequireComponent(typeof(SpriteRenderer))]
[RequireComponent(typeof(Rigidbody2D))]
public class Missile: MonoBehaviour
{
public bool dead = false, hostile = true;
public float speed = 30, rotatingSpeed= 200;
public GameObject target;
private BoxCollider2D bc;
private Rigidbody2D rb;
private SpriteRenderer sr;
private GameObject go;
public Missile() { Debug.Log("Constructed"); }
private void OnEnable()
{
Debug.Log("Missile Launched");
go = new GameObject("Missile");
go.tag = "Missile";
target = GameObject.FindGameObjectWithTag("Ship");
rb = go.AddComponent<Rigidbody2D> ();
sr = go.AddComponent<SpriteRenderer> ();
bc = go.AddComponent<BoxCollider2D>();
bc.size = new Vector2(2f, 2f);
//bc.isTrigger = true;
go.transform.position = new Vector3(0,0, 11);
sr.sprite = SpriteManager.current.GetSprite("Ships", "missile1");
}
private void FixedUpdate()
{
//sr.sprite = SpriteManager.current.GetSprite("Missiles", "missile1");
//Debug.Log(target);
if (!target) return;
var point2Target = (Vector2) go.transform.position - (Vector2) target.transform.position;
point2Target.Normalize();
float value = Vector3.Cross(point2Target, go.transform.right).z;
rb.angularVelocity = rotatingSpeed * value;
//Vector2 lastVel = rb.velocity;
rb.velocity = go.transform.right * speed;
//rb.AddForce(go.transform.right * speed);
}
public void setPosition(int x, int y)
{
go.transform.position = new Vector3(x,y,11);
}
private void OnCollisionEnter2D(Collision2D collision)
{
Debug.Log("hit");
Destroy (go, 0.02f);
}
private void OnTriggerEnter2D(Collider2D other)
{
Debug.Log("hit");
Destroy (go, 0.02f);
}
}
And the second class
[RequireComponent(typeof(SpriteRenderer))]
[RequireComponent(typeof(Rigidbody2D))]
public class Ship: MonoBehaviour
{
public int hull = 100, type = 1;
public bool dead = false;
public float speed = 5, rotatingSpeed= 200;
public GameObject target;
private BoxCollider2D bc;
private Rigidbody2D rb;
private SpriteRenderer sr;
private GameObject go;
public Ship() { Debug.Log("Constructor"); }
private void OnEnable()
{
Debug.Log("Ship Built");
go = new GameObject("Ship");
go.tag = "Ship";
//target = GameObject.FindGameObjectWithTag("Player");
rb = go.AddComponent<Rigidbody2D> ();
sr = go.AddComponent<SpriteRenderer> ();
bc = go.AddComponent<BoxCollider2D>();
bc.size = new Vector2(2f, 2f);;
bc.isTrigger = true;
go.transform.position = new Vector3(0,0,11);
sr.sprite = SpriteManager.current.GetSprite("Ships", "ship2");
//sr.sprite.transform.localScale = anyWidth;
//sr.sprite = SpriteManager.current.GetSprite("Missiles", "missile1");
}
void FixedUpdate ()
{
//Debug.Log(target);
GameObject[] missiles = GameObject.FindGameObjectsWithTag("Missile");
/*foreach (GameObject missile in missiles)
{
Vector2 point2Target = ((Vector2)go.transform.position - (Vector2) missile.transform.position);
if(point2Target.magnitude < 50)
{
point2Target.Normalize();
Flak flak = gameObject.AddComponent<Flak>();
flak.setPosition(go.transform.position);
point2Target.x = point2Target.x * -1;
point2Target.y = point2Target.y * -1;
flak.setVelocity(point2Target * 50);
break;
}
}*/
if (target != null)
{
var point2Target = (Vector2) go.transform.position - (Vector2) target.transform.position;
point2Target.Normalize();
float value = Vector3.Cross(point2Target, go.transform.right).z;
rb.angularVelocity = rotatingSpeed * value;
rb.velocity = go.transform.right * speed;
//Vector2 lastVel = rb.velocity;
//rb.AddForce(go.transform.right * speed;);
}
}
public void setPosition(int x, int y) { go.transform.position = new Vector3(x,y,11); }
private void OnCollisionEnter2D(Collision2D collision)
{
Debug.Log("hit");
Destroy (go, 0.02f);
}
private void OnTriggerEnter2D(Collider2D other)
{
Debug.Log("hit");
Destroy (go, 0.02f);
}
}
and finally the invoking
if (Input.GetKeyUp("i"))
{
var ship = gameObject.AddComponent<Ship>();
ship.setPosition((int)currFramePosition.x, (int)currFramePosition.y);
}
if (Input.GetKeyUp("v"))
{
var missile = gameObject.AddComponent<Missile>();
missile.setPosition((int)currFramePosition.x, (int)currFramePosition.y);
Debug.Log(missile);
}
Some help would be appreciated, thanks.