How to get a projectile to shoot towards a gameobject - c#

Im currently working on a TurretAi. I have it so that when the enemy is within a certain range the turret targets the enemy but I'm unable to get the turret to shoot the projectiles toward the enemy. this is currently what i have this is turret class.
using UnityEngine;
using System.Collections;
public class Defence : MonoBehaviour {
public float DistanceFromCastle,CoolDown;
public GameObject enemy;
public GameObject Bullet;
public int protectionRadius,bulletSpeed;
// Use this for initialization
void Start ()
{
protectionRadius = 35;
bulletSpeed = 50;
CoolDown = 5;
}
// Update is called once per frame
void Update () {
enemy = GameObject.FindGameObjectWithTag("Enemy");
if(enemy != null)
{
DistanceFromCastle = Vector3.Distance(GameObject.FindGameObjectWithTag("Enemy").transform.position,GameObject.FindGameObjectWithTag("Defence").transform.position);
//print (DistanceFromCastle);
if(DistanceFromCastle <= protectionRadius)
{
attackEnemy();
}
}
}
void attackEnemy()
{
transform.LookAt(enemy.transform);
CoolDown -= Time.deltaTime;
if (CoolDown <= 0)
{
Debug.DrawLine(transform.position,enemy.transform.position,Color.red);
Instantiate(Bullet,Vector3.forward,Quaternion.identity);
print("attack Enemy");
CoolDown = 5;
}
}
}
I also already have a cool down var so that it only shoot every 5 second any help would be awesome.

You were fairly close, you need to change this line:
Instantiate(Bullet, Vector3.forward, Quaternion.identity);
To this:
private const int SPAWN_DISTANCE = 5;
Instantiate(Bullet, transform.position + SPAWN_DISTANCE * transform.forward, transform.rotation);
Quaternion.identity refers to:
This quaternion corresponds to "no rotation".

Related

How do I increase speed every time I kill an enemy?

I'm trying to make it so that every time I kill an enemy, my player's speed increases by 1. I've been trying to do this but I don't really know what I'm doing. Can somebody help me?
Here is my player movement script
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float MovementSpeed = 5;
public float JumpForce = 5;
private Rigidbody2D _rigidbody;
private void Start()
{
_rigidbody = GetComponent<Rigidbody2D>();
}
private void Update()
{
//Movement
var movement = Input.GetAxis("Horizontal");
transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * MovementSpeed;
if (Input.GetButtonDown("Jump") && Mathf.Abs(_rigidbody.velocity.y) < 0.001f)
{
_rigidbody.AddForce(new Vector2(0, JumpForce), ForceMode2D.Impulse);
}
}
}
Here is my Enemy script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemyScript : MonoBehaviour
{
public int health = 100;
private static float speed;
private static float jump;
public void TakeDamage(int damage)
{
health -= damage;
if (health <= 0)
{
Die();
speed += 1.0f;
jump += 1.0f;
}
}
void Die()
{
Destroy(gameObject);
speed = GetComponent<PlayerMovement>().MovementSpeed;
jump = GetComponent<PlayerMovement>().JumpForce;
}
}
Sorry, my question didn't have all the details, the player is not gaining any speed. I tried using
GetComponent<PlayerMovement>().MovementSpeed += 1.0f;
GetComponent<PlayerMovement>().JumpForce += 1.0f;
and now I'm getting this error message
NullReferenceException: Object reference not set to an instance of an object
Sorry for the inconvenience
First of all it makes no sense to use GetComponent since the PlayerMovement is not attached to your enemy objects.
Then
speed = GetComponent<PlayerMovement>().MovementSpeed;
jump = GetComponent<PlayerMovement>().JumpForce
is also the wrong way round .. what use would it be to take the value from the player and store it in a field of the enemy?
If there is only one player anyway you could simply use FindObjectOfType and do
void Die()
{
Destroy(gameObject);
FindObjectOfType<PlayerMovement>().MovementSpeed += 1.0f;
FindObjectOfType<PlayerMovement>().JumpForce += 1.0f;
}
Or alternatively use a Singleton Pattern as actually even suggested by before mentioned docs like e.g.
public class PlayerMovement : MonoBehaviour
{
public static PlayerMovement Instance { get; private set;}
private void Awake ()
{
if(Instance && Instance!= this)
{
Destroy(gameObject);
return;
}
Instance = this;
}
...
}
and then simply do
void Die()
{
Destroy(gameObject);
PlayerMovement.Instance.MovementSpeed += 1.0f;
PlayerMovement.Instance.JumpForce += 1.0f;
}
I am assuming you want to increase the jumpforce and speed of your player when the player kills an enemy. Also, Could you please elaborate the question if you are getting any error or just the speed is not increasing?
Please find the inline response for the Enemy Script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemyScript : MonoBehaviour
{
public int health = 100;
private static float speed;//This is enemy speed variable that you have declared
private static float jump;//This is enemy jump variable that you have declared
public void TakeDamage(int damage)
{
health -= damage;
if (health <= 0)
{
Die();
//speed += 1.0f; Here you are increasing enemy speed and not playerspeed.
//jump += 1.0f; Same goes for jump.
}
}
void Die()
{
Destroy(gameObject);
//speed = GetComponent<PlayerMovement>().MovementSpeed; here you are assigning Player movement speed to enemy speed.
//jump = GetComponent<PlayerMovement>().JumpForce; here you are assigning Player movement jump to enemy jump.
//Instead try
GetComponent<PlayerMovement>().MovementSpeed += 1.0f;
GetComponent<PlayerMovement>().JumpForce += 1.0f;
}
}
Also you can use
Debug.Log(your movementspeed variable);
to check if the player speed is being increased or not.

How can I instantiate game objects in Unity (C#) along with an instantiated integer?

I'm trying to have health points to the instantiated enemies of my game.
At first the enemies were just destroyed as soon as a single shot hit them.
I thought adding a new class just holding the HP of the instantiated prefab would work, but I don't know how to write that correctly. Either it's "static" and then I know how to call it from the bullet controller class, but it's not instantiated and the same int value is kept for all instantiated enemies, or it is not "static" and then I don't know how to call it from the other classes.
Here is the code currently, for the bullet controller:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletController : MonoBehaviour
{
private Transform bullet;
public float speed;
// Start is called before the first frame update
void Start()
{
bullet = GetComponent<Transform>();
}
void FixedUpdate()
{
bullet.position += transform.up * speed;
if (bullet.position.y >= 10)
Destroy(gameObject);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Enemy")
{
Enemy4HP.health--;
Destroy(gameObject);
if (Enemy4HP.health < 1)
{
Destroy(other.gameObject);
PlayerScore.playerScore++;
}
}
if (other.tag == "Enemy2")
{
Enemy10HP.health--;
Destroy(gameObject);
if (Enemy10HP.health <1)
{
Destroy(other.gameObject);
PlayerScore.playerScore++;
}
}
}
}
and for the two health classes:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy4HP : MonoBehaviour
{
public int health = 4;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy10HP : MonoBehaviour
{
public int health = 10;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
And this is how the enemies get instantiated:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EnemyController : MonoBehaviour
{
private Transform enemyHolder;
public float speed;
public GameObject shot;
public GameObject enemy;
public GameObject enemy2;
public Text winText;
int secCount;
float timer = 0;
public float fireRate = 0.997f;
public int enemyCount;
// Start is called before the first frame update
void Start()
{
enemyCount = 0;
secCount = 0;
enemyHolder = GetComponent<Transform>();
winText.enabled = false;
InvokeRepeating("MoveEnemy", 0f, 0.016f);
}
private List<GameObject> allSpawns = new List<GameObject>();
void MoveEnemy()
{
float xPosition = Random.Range(-11f, 11f);
int enemyType = Random.Range(0, 8);
secCount = Random.Range(2, 4);
timer += Time.deltaTime;
if (timer >= secCount && enemyCount < 25)
{
if (enemyType > 0)
{
GameObject spawned = Instantiate(enemy, new Vector3(xPosition, 6, 0), Quaternion.identity);
allSpawns.Add(spawned);
}
else
{
GameObject spawned = Instantiate(enemy2, new Vector3(xPosition, 6, 0), Quaternion.identity);
allSpawns.Add(spawned);
}
enemyCount++;
timer = timer - secCount;
}
foreach (GameObject thisEnemy in allSpawns)
{
if (thisEnemy !=null)
{
thisEnemy.transform.position += new Vector3(0, -1 * speed * Time.deltaTime, 0);
}
}
if (PlayerScore.playerScore == 25)
{
timer = 0;
CancelInvoke();
InvokeRepeating("MoveEnemy2", 0f, 0.016f);
}
}
...
That returns "An object reference is required for the non_static field...". What can I do?
Thanks.
Simplest quickest. Instead of 2 classes with 2 different number make 1 called EnemyHP. Add the component to the enemy prefabs and on the prefab in the inspector set the component's health to 4 for enemy 1 and 10 for enemy 2. Then :
void OnTriggerEnter2D(Collider2D other)
{
//you can probably just make both enemy the same tag.
if (other.tag == "Enemy" || other.tag == "Enemy2")
{
//get the Hp component of the specific enemy.
EnemyHP hpComponent = other.gameObject.GetComponent<EnemyHP>();
hpComponent.health--;
Destroy(gameObject);
if (hpComponent.health < 1)
{
Destroy(other.gameObject);
PlayerScore.playerScore++;
}
}
}

How to make enemies turn and move towards player when near? Unity3D

I am trying to make my enemy object turn and start moving towards my player object when the player comes within a certain vicinity.
For the turning I have been testing the transform.LookAt() function although it isn't returning the desired results as when the player is too close to the enemy object the enemy starts to tilt backwards and I only want my enemy to be able to rotate along the y axis, thanks in advance.
using UnityEngine;
using System.Collections;
public class EnemyController : MonoBehaviour {
public Transform visionPoint;
private PlayerController player;
public Transform Player;
public float visionAngle = 30f;
public float visionDistance = 10f;
public float moveSpeed = 2f;
public float chaseDistance = 3f;
private Vector3? lastKnownPlayerPosition;
// Use this for initialization
void Start () {
player = GameObject.FindObjectOfType<PlayerController> ();
}
// Update is called once per frame
void Update () {
// Not giving the desired results
transform.LookAt(Player);
}
void FixedUpdate () {
}
void Look () {
Vector3 deltaToPlayer = player.transform.position - visionPoint.position;
Vector3 directionToPlayer = deltaToPlayer.normalized;
float dot = Vector3.Dot (transform.forward, directionToPlayer);
if (dot < 0) {
return;
}
float distanceToPlayer = directionToPlayer.magnitude;
if (distanceToPlayer > visionDistance)
{
return;
}
float angle = Vector3.Angle (transform.forward, directionToPlayer);
if(angle > visionAngle)
{
return;
}
RaycastHit hit;
if(Physics.Raycast(transform.position, directionToPlayer, out hit, visionDistance))
{
if (hit.collider.gameObject == player.gameObject)
{
lastKnownPlayerPosition = player.transform.position;
}
}
}
}
change the look at target:
void Update () {
Vector3 lookAt = Player.position;
lookAt.y = transform.position.y;
transform.LookAt(lookAt);
}
this way the look at target will be on the same height as your object.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EnemyMovement : MonoBehaviour
{
public Transform Player;
public float MoveSpeed = 4;
int MaxDist = 10;
int MinDist = 5;
void Update()
{
transform.LookAt(Player);
if (Vector3.Distance(transform.position, Player.position) >= MinDist)
{
transform.position += transform.forward * MoveSpeed * Time.deltaTime;
if (Vector3.Distance(transform.position, Player.position) <= MaxDist)
{
// Put what do you want to happen here
}
}
}
}

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.

how to shoot in the mouse pointer angle?

I have a player which is shooting with bullets to the enemy,the bullets are moving towards the right,in a correct angle,but my bullet is not pointing towards that angle,the bullets is unable to change its angle.,how to change it?,it should not only move in that angle but also point towards it,currently i am transforming it to right of the screen.,the enemy are spawning from the right.here is my code for movement and transformation,any help thanx,
this is the code for direction,and for the shooting rate
using UnityEngine;
using System.Collections;
public class WeaponScript : MonoBehaviour
{
public Transform shotPrefab;
public float shootingRate = 0.25f;
private float shootCooldown;
void Start()
{
shootCooldown = 0f;
}
void Update()
{
if (shootCooldown > 0)
{
shootCooldown -= Time.deltaTime;
}
}
public void Attack(bool isEnemy)
{
if (CanAttack)
{
shootCooldown = shootingRate;
// Create a new shot
var shotTransform = Instantiate(shotPrefab) as Transform;
// Assign position
shotTransform.position = transform.position;
// The is enemy property
ShotScript shot = shotTransform.gameObject.GetComponent<ShotScript>();
if (shot != null)
{
shot.isEnemyShot = isEnemy;
}
// Make the weapon shot always towards it
MoveScript move = shotTransform.gameObject.GetComponent<MoveScript>();
if (move != null)
{
move.direction = this.transform.right;
}
}
}
public bool CanAttack
{
get
{
return shootCooldown <= 0f;
}
}
}
this is the code for movement
using UnityEngine;
using System.Collections;
public class MoveScript : MonoBehaviour {
public Vector2 speed = new Vector2(10,10);
public Vector2 direction = new Vector2(1,0);
void Update () {
Vector3 movement = new Vector3 (speed.x * direction.x, speed.y * direction.y, 0);
movement *= Time.deltaTime;
transform.Translate(movement);
}
}
Using transform.LookAt(transform.position + direction) will immediately point your object in the specified direction.

Categories