logo
down
shadow

Constant Enemy Damage to Player - Unity 2019.1 Beta


Constant Enemy Damage to Player - Unity 2019.1 Beta

By : user2187105
Date : November 26 2020, 04:01 AM
this will help OnCollisionEnter2D is meant to trigger only the first frame the same collision occurs.
You want to use OnCollisionStay2D(), which triggers on every frame with a collision.
code :
private void OnCollisionStay2D(Collision2D collision)
{
    if (collision.gameObject.tag == "Enemy01")
    {
        GetComponent<AudioSource>().Play();

        // To take 5 - 30 damage per second:
        HPBAR.PlayHP -= Random.Range(5f,30f) * Time.deltaTime;

        if (HPBAR.PlayHP < 0)// Insures player HP bar doesn't read less than zero in GUI TXT
        {
            HPBAR.PlayHP = 0;

        }
        // Debug.Log("Ouch! " + HPBAR.PlayHP + " Left");
        if (HPBAR.PlayHP <= 0 && HPBAR.lives > 0)
        {
            HPBAR.lives--;
            HPBAR.LPfloat--;
            p5.transform.position = spawner.transform.position;
            HPBAR.PlayHP = Random.Range(100, 150);
            // Debug.Log("You're Dead!!! Lives left: " + (HPBAR.lives + 1));

        }
        else if (HPBAR.PlayHP <= 0 && HPBAR.lives <= 0)
        {
            SceneManager.LoadScene("DeathScene");
        }

    } // of player tag check

}// end of collision stay

private void OnCollisionExit2D(Collision2D collision)
{
    if (collision.gameObject.tag == "Enemy01")
    {
        // put "i quit touching the hurty thing" stuff here.
    }
}


Share : facebook icon twitter icon
Unity - Enemy AI; Run away from player (x and y)

Unity - Enemy AI; Run away from player (x and y)


By : Matt M
Date : March 29 2020, 07:55 AM
should help you out You want the campers to run away from the player right? Then you should do
code :
Vector3 moveDirection = transform.position - Player.transform.position
character.Move(moveDirection.normalized * speed * Time.deltaTime);
Instantiated Enemy outputs double damage for every enemy spawning after him

Instantiated Enemy outputs double damage for every enemy spawning after him


By : Diego Solis
Date : March 29 2020, 07:55 AM
it fixes the issue There are a few problems with your scripts...
I don't think you understand what a static variable is.
code :
public static bool inSight;
PlayerMovement.isEnemyAttacking
using UnityEngine;
using UnityEngine.UI;

public class PlayerHealth : MonoBehaviour
{
    public static float Health;
    public static float maxHealth = 100;

    private Text healthText;


    void Start()
    {
        healthText = GameObject.FindGameObjectWithTag("HealthPoints").GetComponent<Text>();

        //Make it full 100% health on start
        Health = maxHealth;
        RefreshHealthBar();
    }



    public void TakeDamage(float damage)
    {
        Health -= damage;
        RefreshHealthBar();

        if (Health <= 0)
            Die();
    }

    public void Die()
    {
        Health = 0;
        RefreshHealthBar();

        //TODO: Your code
    }

    void RefreshHealthBar()
    {
        healthText.text = "HEALTH: " + Health;
    }
}
 using System.Collections;
using UnityEngine;

public class EnnemyAI : MonoBehaviour
{
    public float AttackDamage = 1.0f;
    public float AttackSpeed = 1.0f;
    public float AttackRange = 1.0f;

    private bool isPlayerInSight;
    private GameObject target;
    private NavMeshAgent agent;


    // Use this for initialization
    void Start ()
    {
        target = GameObject.FindGameObjectWithTag("Player");
        agent = GetComponent<NavMeshAgent>();

        StartCoroutine(AttackLoop());
    }

    // Update is called once per frame
    void Update ()
    {
        if (isPlayerInSight)
        {
            agent.destination = target.transform.position;
        }
    }

    IEnumerator AttackLoop()
    {
        while (true)
        {
            //I don't know your attacking logic, so lets say they can attack in a 1 unit range
            while (Vector3.Distance(target.transform.position, this.transform.position) <= AttackRange)
            {
                Attack();
                yield return new WaitForSeconds(AttackSpeed);
            }

            yield return 0;
        }
    }

    void Attack()
    {
        target.GetComponent<PlayerHealth>().TakeDamage(AttackDamage);
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Player")
        {
            isPlayerInSight = true;
        }
    }

    void OnTriggerExit(Collider other)
    {
        if (other.gameObject.tag == "Player")
        {
            isPlayerInSight = false;
        }
    }
}
Unity Survival Shooter Enemy taking no damage - Android

Unity Survival Shooter Enemy taking no damage - Android


By : faris zaini
Date : March 29 2020, 07:55 AM
this will help You are already using Layer to make sure that the raycast hit just the GameObjects on the shootableMask layer which is the "Shootable" layer so layer issue problem is eliminated.
The only possible problem left is that the EnemyHealth script is not attached to the GameObject or maybe some of the GameObjects.
Cause player to take damage in Unity 2D

Cause player to take damage in Unity 2D


By : user2066269
Date : March 29 2020, 07:55 AM
Any of those help I made two scripts. One that'll keep track of the player's health, health bar and cause the screen to flash when the player is damaged. The other script is meant to be placed on any object I wish to do damage to the player, on contact. My problem is, Nothing seems to be doing any damage to the player. ,
Make sure that the players Collider has isTrigger enabled.
code :
[Range(1,100)] public int attackDamage = 10;
private void OnTriggerEnter2D(Collider2D col)
{
    // gets PlayerHealth component on this or any parent object
    var health = col.GetComponentInParent<PlayerHealth>();
    if (health  == playerHealth)
    {
        Attack();
    }
}
private void Update()
{
    damaged = false;
}

public void TakeDamage(int amount)
{
    damaged = true;
    currentHealth -= amount;
    healthSlider.value = currentHealth;
}
player = GameObject.FindGameObjectWithTag("Player");
playerHealth = player.GetComponent<PlayerHealth>();
playerHealth = FindObjectOfType<PlayerHealth>();
private void OnTriggerEnter2D(Collider2D col)
{
    // gets PlayerHealth component on this or any parent object
    var health = col.GetComponentInParent<PlayerHealth>();
    if (health != null)
    {
        Attack(health);
    }
}

void Attack(PlayerHealth health)
{
    timer = 0f;
    if(health.currentHealth > 0)
    {
        health.TakeDamage(attackDamage);
    }
}
Unity 2D rotate the AI enemy to look at player

Unity 2D rotate the AI enemy to look at player


By : Joshua Evenson
Date : March 29 2020, 07:55 AM
I hope this helps . You need a function that would flip your sprite, you can do that by changing the scale of the transform, and keep a boolean to check where it's facing bool facingRight;, so something like this
code :
void Flip(){
      Vector3 scale = transform.localScale;
      scale.x *= -1;
      transform.localScale = scale;
      facingRight = !facingRight;
}
if (Vector3.Distance(target.position,transform.position)<20)
    {

     transform.position=Vector2.MoveTowards(transform.position, target.position,speed*Time.deltaTime);
     if(target.position.x > transform.position.x && !facingRight) //if the target is to the right of enemy and the enemy is not facing right
        Flip();
     if(target.position.x < transform.position.x && facingRight)
        Flip();
   }
Related Posts Related Posts :
  • Linq to object Multiple Where short circuit evaluation
  • WPF - Create solid layout without designer
  • View not rendering on NET Core
  • Proper way to create domain models and viewmodels in microservices
  • StaticInjectorError(AppModule)[AuthGuard] after login
  • Getting Entity Model dynamically based on TableName?
  • Customizing the Navigation Form after my form's confirmation dialog
  • CSHTML Confirm Delete prior to deleting database record
  • How to set property values for indexers using Expressions?
  • My Mandelbrot sketching program in c# isn't working
  • Best way to validate a date string in C#
  • Bot Framework v4 Bot emulator authentication bad request
  • Can I use MVC 5 remote validation to check for duplicate values, but exclude the item being edited?
  • How to get list of all databases using MongodbClient class. (C# application)
  • WPF DataGrid disable cell edit based on value
  • how to check if there are 4 or more spaces in streamread line
  • How to perform style changes on datagridview rows using rows from the underlying bindingsource?
  • How do I add a C# solution file in Jetbrains Rider?
  • Docker ASP.NET CORE 2.1 app in Visual Studio 2017. App does not start in debug mode
  • ASP.NET Core WebApi with SQL Server and EFCore 2
  • Sitefinity Widget User Control
  • MultiSelectList shows one value from the IEnumerable given to it with multiple values
  • Items in picker from a list - Xamarin Code behind
  • How can I insert/update a List<T> as member of an entity in SQLite?
  • How to "flush" ApplicationInsightsTraceListener, in a Console Application, on exit?
  • Named Pipes Between Winforms and Service Can Only Connect Once
  • Add CDATA to a Node Value in a loop
  • Custom serializer for just one property in Json.NET, without changing the model class
  • How to stop a timer/change system UI OnSleep Xamarin Android
  • LINQ parse xml file and get values from specific nodes
  • How do I set the time out for page load?
  • Clarification of IL generated code referenced to strings
  • EntityFrameworkCore.SQLLite and UWP Not behaving as expected
  • WPF MediaElement: Video opened twice
  • Temporary excel file with Interop library
  • Insert \u2265 into a C# string
  • Is there a way to scan for viruses when downloading an attachment using EWS?
  • How to generify a method when T can be multiple new () Types?
  • Reading binary file data into List of Structs
  • Updating Status Strip on Form from BackgroundWorker
  • Visual Studio using GIT repository Publishing with API and Website in one Solution
  • Return Standard Deviation of column values with other column value condition LINQ
  • Grab a count of different values in object
  • c# File used by who?
  • How to parse string into an array using set number of characters in C#
  • How to sent list using CommandParameter
  • Problem with referencing ResourceDictionaries, and Styling across multiple assemblies
  • StackExchange Redis - high CPU usage on WriteAllQueues
  • Not typing the full variable name but partial name is represented by another string value
  • Linq to Entities Selecting Data with Max Date?
  • How to extract data using Ical.Net?
  • C# program crashes because listbox items change
  • Kicking a user in Discord.Net
  • C# Linq Find duplicates with multiple group by
  • How to call control on a Panel that is inside usercontrol
  • c# ReadAsJsonAsync in framework 4.5
  • Inner join two table variables and return an output cursor from an anonymous plsql block in a c# application
  • Notify consumers when all tasks have completed without blocking the thread
  • Replace "\\" with "\" in a path
  • CSS Not formatting inside repeater
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org