unity3D, enemy following issue - c#

I'm trying to make enemies follow my player when the player enters the radius area of an enemy, but make the enemy stop following when my bullet hits object or enters radiusArea.
See my gif for more detail:
Gif
script:
using UnityEngine;
using System.Collections;
public class FlyEnemyMove : MonoBehaviour
{
public float moveSpeed;
public float playerRange;
public LayerMask playerLayer;
public bool playerInRange;
PlayerController thePlayer;
// Use this for initialization
void Start()
{
thePlayer = FindObjectOfType<PlayerController>();
}
// Update is called once per frame
void Update()
{
flip();
playerInRange = Physics2D.OverlapCircle(transform.position, playerRange, playerLayer);
if (playerInRange)
{
transform.position = Vector3.MoveTowards(transform.position, thePlayer.transform.position, moveSpeed * Time.deltaTime);
//Debug.Log(transform.position.y);
}
//Debug.Log(playerInRange);
}
void OnDrawGizmosSelected()
{
Gizmos.DrawWireSphere(transform.position, playerRange);
}
void flip()
{
if (thePlayer.transform.position.x < transform.position.x)
{
transform.localScale = new Vector3(0.2377247f, 0.2377247f, 0.2377247f);
}
else
{
transform.localScale = new Vector3(-0.2377247f, 0.2377247f, 0.2377247f);
}
}
}
I hope someone can help me :(

Physics2D.OverlapCircle detects only the collider with the lowest z value (if multiple are in range). So you either need to change the z values so the player has the lowest or you need to work with Physics2D.OverlapCircleAll and check the list to find the player. Or you could change your layers so only the player itself is on that specific layer you feed into the overlap test.

Related

How to throw a ball that player picked up in Unity 2d project

I have a problem with writing a function that throws spawned ball by pressing a button.
So far, i could only instantiate the ball and it is affected by gravity.
I can not wrap my head arround, how in my code should i add a force to push it with some force. Right now it just plops in front of a player.
I tried to fiddle with .AddForce() on a ball rigidbody2D and still nothing.
I would greatly appreciate if someone could take a look at the code and guide me into some directcion on where to AddForce for ball to make it move?
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerControl : MonoBehaviour
{
[Header("Player Atributes")]
[SerializeField] float runSpeed = 10f;
Vector2 moveInput;
Rigidbody2D playerRigidbody2D;
[Header("Ball Settings")]
public bool playerHasABall = false;
[SerializeField] GameObject ball;
[SerializeField] Transform ballSpawn;
void Start()
{
playerRigidbody2D = GetComponent<Rigidbody2D>();
}
void Update()
{
Run();
FlipSprite();
}
void OnMove(InputValue value)
{
moveInput = value.Get<Vector2>();
}
void OnFire(InputValue value)
{
if(!playerHasABall) {return;}
Instantiate(ball, ballSpawn.position, transform.rotation);
playerHasABall = false;
}
void Run()
{
Vector2 playerVelocity = new Vector2 (moveInput.x * runSpeed, playerRigidbody2D.velocity.y);
playerRigidbody2D.velocity = playerVelocity;
}
void FlipSprite()
{
bool playerHasHorizontalSpeed = Mathf.Abs(playerRigidbody2D.velocity.x) > Mathf.Epsilon;
if (playerHasHorizontalSpeed)
{
transform.localScale = new Vector2 (Mathf.Sign(playerRigidbody2D.velocity.x), 1f);
}
}
//Ball picking up script. It destroys the ball with a tag "Ball" and sets a bool playerHasABall to true
private void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Ball")
{
Destroy(other.gameObject);
playerHasABall = true;
}
}
}
So, i manage to fiddle with the .AddForce() method once again and i came up with a solution to my problem.
My OnFire script looks like this:
void OnFire(InputValue value)
{
if(!playerHasABall) {return;}
Instantiate(ball, ballSpawn.position, transform.rotation);
playerHasABall = false;
}
No change here. I made another script called "BallBehaviour.cs" and added it to the ball with a code like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallBehaviour : MonoBehaviour
{
[SerializeField] float ballForce = 20f;
PlayerControl player;
void Start()
{
player = FindObjectOfType<PlayerControl>();
Throw();
}
public void Throw()
{
GetComponent<Rigidbody2D>().AddForce(player.transform.localScale * ballForce, ForceMode2D.Impulse);
}
}
Basically, the method Throw() tells the ball to check the direction the player is facing and then multiply it by ballForce. Then, it uses the ForceMode2d.Impulse method to apply calculated force to the ball for a second and it works on left or right direction.
Thanks Jkimishere for a nudge in a propper direction!
You might need a variable to check if the player is facing right/left.
If the player is, just add force to the ball depending on the direction.
if(!playerHasABall) {return;}
Instantiate(ball,
ballSpawn.position,
transform.rotation);
//Check which way the player is facing and add forrce to that direction.
//Adding a FacingRight boolean might help.....
playerHasABall = false;

Unity prefab movement

Hello i want to create a group of the same prefab following the player in my game. I already got the prefab intantiation to follow the player but when there is more than one they just follow the exact same path on top of each other. is there a way where they can follow the player but act like a bunch of bees moving?
Thanks!
This is the script on my prefab:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KillerMovement : MonoBehaviour {
public GameObject player;
void FixedUpdate()
{
Vector2 toTarget = player.transform.position - transform.position;
float speed = 0.5f;
transform.Translate(toTarget * speed * Time.deltaTime);
}
}
The best solution depends on you game logic, but you may consider having a delay before starting following (you can tweak the delay depending on the position you want to the particular object to assume in the trail.
using System.Collections;
using UnityEngine;
public class Follower : MonoBehaviour
{
public GameObject player;
public float delay = 0f;
public float speed = .5f;
bool isReady = false;
void Start()
{
StartFollowing();
}
public void StartFollowing()
{
StartCoroutine(WaitThenFollow(delay));
}
IEnumerator WaitThenFollow(float delay)
{
yield return new WaitForSeconds(delay);
isReady = true;
Debug.Log(gameObject.name);
Debug.Log(Time.time);
}
void FixedUpdate()
{
if (isReady && player != null)
{
Vector2 toTarget = player.transform.position - transform.position;
transform.Translate(toTarget * speed * Time.deltaTime);
}
}
}
I've called StartFollowing in the Start method for you to test the code. You should call this method whenever approrpiate in your game logic.

How do I stop AI movement with OnTriggerEnter2D in Unity?

I'm creating a basic AI script for my enemies in Unity and I have most of it working the way I want it to. The way I have my enemies set up they contain 2 colliders, a polygon collider that destroys the player when touched, and an empty game object that's a child of the enemy that is a circle collider that acts as a trigger. There's a game object that's tagged Straight Road and when the circle collider comes in contact with it, it should run a function called StopMovement(); that sets the enemies movement to 0. I used to Debug.Log(); to check to see if the collider recognizes that it's touching Straight Road and it doesn't. This is my code below. I'm hoping someone has a suggestion.
public class DogAI : GenericController {
public Transform target;
public float chaseRange;
public float maxDistance;
private Vector3 targetDirection;
private float targetDistance;
// Use this for initialization
void Start()
{
base.Start();
}
// Update is called once per frame
void Update()
{
base.Update();
if (target.transform != null)
{
targetDirection = target.transform.position - transform.position;
targetDirection = targetDirection.normalized;
targetDistance = Vector3.Distance(target.position, transform.position);
if (targetDistance <= chaseRange)
{
SetMovement(targetDirection);
}
Vector3 enemyScreenPosition = Camera.main.WorldToScreenPoint(transform.position);
if (targetDistance > maxDistance)
{
Destroy(gameObject);
}
}
}
void StopMovement()
{
SetMovement(new Vector2(0,0));
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Straight Road"))
{
Debug.Log("Stop! There's a road!");//This never shows up in the log?
StopMovement();
}
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("Player"))
{
DestroyObject(other.gameObject);
}
}
Generic Controller script below containing the SetMovement() function.
public abstract class GenericController : MonoBehaviour
{
public float movementSpeed = 20;
float animationSpeed = 1;
protected Rigidbody2D rigidbody;
protected Animator animator;
Vector2 movementVector;
float currentSpeed;
protected bool needAnimator = true;
// Use this for initialization
protected void Start()
{
rigidbody = GetComponent<Rigidbody2D>();
if (needAnimator)
{
animator = GetComponent<Animator>();
animator.speed = animationSpeed;
}
}
protected void FixedUpdate()
{
rigidbody.velocity = movementVector;
currentSpeed = rigidbody.velocity.magnitude;
if (needAnimator)
animator.SetFloat("Speed", currentSpeed);
}
public void SetMovement(Vector2 input)
{
movementVector = input * movementSpeed;
}
public void SetMovement(int x, int y)
{
SetMovement(new Vector2(x, y));
}
From the documentation:
MonoBehaviour.OnTriggerEnter2D(Collider2D)
Sent when another object enters a trigger collider attached to this object (2D physics only).
The keyword here is enters. In other words, a trigger is for when something goes inside the area of the collider, like a player entering a region of the map, where the region is a trigger collider. If you want something to happen when a collider collides with the road, i.e. when your CircleCollider comes in contact with the road, then you want the collider to not be a trigger, and you want the functionality to be inside OnCollisionEnter2D.

How can i make that the user can select if the camera will be behind the player or not?

This is the original code make the camera follow the player:
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour
{
public GameObject objectToFollow; //Public variable to store a reference to the player game object
private Vector3 offset; //Private variable to store the offset distance between the player and camera
// Use this for initialization
void Start()
{
//Calculate and store the offset value by getting the distance between the player's position and camera's position.
offset = transform.position - objectToFollow.transform.position;
}
// LateUpdate is called after Update each frame
void LateUpdate()
{
// Set the position of the camera's transform to be the same as the player's, but offset by the calculated offset distance.
transform.position = objectToFollow.transform.position + offset;
transform.LookAt(objectToFollow.transform);
}
}
And this is what i tried to do but then the player it self(ThirdPersonController) is not rotating according to where he move.
With the original script above he does.
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour
{
public GameObject objectToFollow; //Public variable to store a reference to the player game object
public bool behindPlayer = false;
private Vector3 cameraStartPos;
// Use this for initialization
void Start()
{
cameraStartPos = transform.position;
// Put the camera behind the player
if (behindPlayer == true)
{
transform.position = (objectToFollow.transform.position - (objectToFollow.transform.forward * 5) + (objectToFollow.transform.up * 2));
}
}
private void Update()
{
if (behindPlayer == true)
{
transform.position = (objectToFollow.transform.position - (objectToFollow.transform.forward * 5) + (objectToFollow.transform.up * 2));
}
else
{
transform.position = cameraStartPos;
}
}
// LateUpdate is called after Update each frame
void LateUpdate()
{
transform.position = objectToFollow.transform.position;
transform.LookAt(objectToFollow.transform);
}
}
I want that the camera will be automatic behind the player already without the need to change the camera position in the scene if the user want by using the bool variable.
But the script now is not like in the above:
With this line in the LateUpdate:
transform.position = objectToFollow.transform.position;
Using the bool false/true it's not changing the camera position at all.
Without this line the player will move and the camera will follow but the player will not rotate and not move as above.
What i want is just like the first script but with the behindPlayer variable.
A working script:
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour
{
[SerializeField]
private Transform target;
[SerializeField]
private Vector3 offsetPosition;
[SerializeField]
private Space offsetPositionSpace = Space.Self;
[SerializeField]
private bool lookAt = true;
private void Update()
{
Refresh();
}
public void Refresh()
{
if (target == null)
{
Debug.LogWarning("Missing target ref !", this);
return;
}
// compute position
if (offsetPositionSpace == Space.Self)
{
transform.position = target.TransformPoint(offsetPosition);
}
else
{
transform.position = target.position + offsetPosition;
}
// compute rotation
if (lookAt)
{
transform.LookAt(target);
}
else
{
transform.rotation = target.rotation;
}
}
}
In the inspector set the offset for example to 0,5,-12 and as target set for example ThirdPersonController. And attach the script to the Camera(Camera must be tagged as MainCamera if the target is ThirdPersonController since the ThirdPersonController ThirdPersonUserControl script is looking for the MainCamera).
And the camera doesn't have to be a child of the target the camera can be in any place in the Hierarchy.
Anyway it's working.

Trying to launch a projectile towards a gameobject, doesn't move!=

I'm making a 2D Tower Defense game and want my towers to launch a prefab at minions. However it currently only spawns my desired prefab, but doesn't move it.
My two scripts:
public class Attacker : MonoBehaviour {
// Public variables
public GameObject ammoPrefab;
public float reloadTime;
public float projectileSpeed;
// Private variables
private Transform target;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider co){
if (co.gameObject.tag == "Enemy" || co.gameObject.tag == "BlockTower") {
Debug.Log("Enemy tag detected");
if(this.gameObject.tag == "Enemy" && co.gameObject.tag != "Enemy"){
Debug.Log("This is an Enemy");
// Insert for Enemey to attack Block Towers.
}
if(this.gameObject.tag == "Tower" && co.gameObject.tag != "BlockTower"){
Debug.Log("This is a Tower");
Tower Tower = GetComponent<Tower>();
Tower.CalculateCombatTime(reloadTime, projectileSpeed);
Transform SendThis = co.transform;
Tower.SetTarget(SendThis);
}
}
}
}
and
public class Tower : MonoBehaviour {
private Transform target;
private float fireSpeed;
private double nextFireTime;
private GameObject bullet;
private Attacker source;
// Use this for initialization
public virtual void Start () {
source = this.GetComponent<Attacker> ();
}
// Update is called once per frame
public virtual void Update () {
if (target) {
Debug.Log("I have a target");
//if(nextFireTime <= Time.deltaTime)
FireProjectile ();
}
}
public void CalculateCombatTime(float time, float speed){
Debug.Log("Calculate Combat Speed");
nextFireTime = Time.time + (time * .5);
fireSpeed = speed;
}
public void SetTarget(Transform position){
Debug.Log("Set Target");
target = position;
}
public void FireProjectile(){
Debug.Log("Shoot Projectile");
bullet = (GameObject)Instantiate (source.ammoPrefab, transform.position, source.ammoPrefab.transform.rotation);
float speed = fireSpeed * Time.deltaTime;
bullet.transform.position = Vector3.MoveTowards (bullet.transform.position, target.position, speed);
}
}
Basicly Attacker detects the object that collides with it, then if its tag is Tower it will send the information to Tower. My debug shows that every function works, even "Debug.Log("Shoot Projectile");" shows up.
However it doesn't move towards my target so I guess "bullet.transform.position = Vector3.MoveTowards (bullet.transform.position, target.position, step);" is never being executed?
Vector3.MoveTowards only moves the object once, it's just a instant displacement when the FireProjectile is called.
You need to create some kind of projectile script with an Update() function to make it move over time.
Here is an example:
public class Projectile : MonoBehaviour
{
public Vector3 TargetPosition;
void Update()
{
transform.position = Vector3.MoveTowards(transform.position, TargetPosition, speed * Time.DeltaTime);
}
}
Then right after your bullet instantiation, set the target:
bullet.GetComponent<Projectile>().TargetPosition = target.position;
Hope it helps.
You have to update the position of the bullet. You are only moving when you create the bullet.
Try to make a list of bullets and use the update function to change the position.

Categories