Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by svetliaka92 · Aug 22, 2015 at 06:17 AM · c#unity 4.6

[HELP] How to make an object spawn and follow the player

Hello. I'm trying to build a laser defender type of game. I added some power-ups to fall from enemies at a random probability. I've decided to add a power-up that spawns a new player ship that has to follow the players ship. How can i make the new spawn move on it's own and follow the player (like in the Super Gradius NES game if someone still remembers it, where you could spawn a red orb following the player and shooting with the same power and fire rate as the player). I mean the clone should start to move when the player's ship is at an X distance away from the clone.

Here is what i mean in pictures:

alt text

alt text

Here are the codes for the player and the player clone:

Player:

using UnityEngine; using UnityEngine.UI; using System.Collections;

public class PlayerController : MonoBehaviour { public float speed = 3.0f; public float padding = 1f; public GameObject[] projectiles = new GameObject[15]; public GameObject[] ships = new GameObject[3]; public float projectileSpeed; public float fireRate = 0.2f; public int health = 100; public int armor = 100; public int damag = 100; //public Canvas canvas; //public Sprite[] laserSprites = new Sprite[15]; public int amountUpgrades; public PlayerClone[] playerClones = new PlayerClone[3];

 public AudioClip destroyed;
 public AudioClip shoot;

 float xmin;
 float xmax;
 int i = 0;
 public int newArmor;
 public int newHealth;
 public float newSpeed;
 public static int newDamage;

 int dmgUp = 0;
 int projectilesIndex = 0;
 LevelManager levelmanager;

 void Start(){
     if(Application.loadedLevelName == "02 Level_01"){
         newArmor = armor;
         newHealth = health;
         newSpeed = speed;
         newDamage = damag;
     }
     // Defining the play space edges
     float distance = transform.position.z - Camera.main.transform.position.z;
     Vector3 leftmost = Camera.main.ViewportToWorldPoint(new Vector3(0,0,distance));
     Vector3 rightmost = Camera.main.ViewportToWorldPoint(new Vector3(1,0,distance));
     xmin = leftmost.x + padding;
     xmax = rightmost.x - padding;
     Debug.Log(newArmor);
     Debug.Log(newHealth);
     Debug.Log(newDamage);
     Debug.Log(newSpeed);
 }

 void Update () {
     // Moving left or right
     if(Input.GetKey(KeyCode.LeftArrow)){
         transform.position += Vector3.left * speed * Time.deltaTime;
     }else if(Input.GetKey(KeyCode.RightArrow)){
         transform.position += Vector3.right * speed * Time.deltaTime;
     }

     // Resctricting the player to the game space
     float newX = Mathf.Clamp(transform.position.x,xmin,xmax);
     transform.position = new Vector3(newX,transform.position.y,transform.position.z);

     // Creating lasers when space is pressed
     if(Input.GetKeyDown(KeyCode.Space)){
         InvokeRepeating("Fire", 0.000001f, fireRate);
     }
     if(Input.GetKeyUp(KeyCode.Space)){
         CancelInvoke("Fire");
     }
 }

 void OnTriggerEnter2D (Collider2D collider){
     EnemyProjectile missile = collider.gameObject.GetComponent<EnemyProjectile>();
     if (missile) {
         //Debug.Log ("Enemy scored a hit!");
         Debug.Log(health);
         if(EnemyProjectile.damage > armor){
             health -= missile.GetDamage () - armor;
             Debug.Log(health);
             missile.Hit ();
         }else{
             missile.Hit();
         }

     }
     if (health <= 0) {
         Die ();
     }

     PowerUps Powerup = collider.gameObject.GetComponent<PowerUps>();
     if(Powerup){
         //Debug.Log("Power up");
         if(Powerup.armorUpgrade != 0){
             //Debug.Log("Armor");
             newArmor += Powerup.ArmorUpgrade();
             Debug.Log(newArmor);
         }else if(Powerup.damageUpgrade != 0){
             //Debug.Log("Damage");
             newDamage += Powerup.DamageUpgrade();
             dmgUp++;
             //Debug.Log(missile.damage);
             //Debug.Log(dmgUp);
             if(projectilesIndex < 15){
                 if(dmgUp == amountUpgrades){
                     projectilesIndex++;
                     dmgUp = 0;
                 }
             }

         }else if(Powerup.speedUpgrade != 0){
             Debug.Log("Speed");
             newSpeed += Powerup.SpeedUpgrade();
             Debug.Log(newSpeed);
         }else if(Powerup.healthReturn != 0){
             Debug.Log("Health");
             newHealth += Powerup.HealthUpgrade();
             Debug.Log(newHealth);
         }else if(Powerup.doubleShip != 0){
             if(i <= 2){
                 Instantiate(ships[i],transform.position,Quaternion.identity);
                 i++;
             }                
         }
         Powerup.Hit();
     }
 }

 void Die(){
     //man = GameObject.Find("LevelManager").GetComponent<LevelManager>();
     levelmanager = GameObject.Find("LevelManager").GetComponent<LevelManager>();
     levelmanager.LoadLevel("03b Lose");
     Destroy(gameObject);
 }

 void Fire(){
     Vector3 offset = new Vector3(0,1,0);
     GameObject beam = Instantiate(projectiles[projectilesIndex], transform.position + offset, Quaternion.identity) as GameObject;
     beam.rigidbody2D.velocity = new Vector3(0,projectileSpeed,0);
     AudioSource.PlayClipAtPoint(shoot,transform.position);
 }

}

Player Clone:

using UnityEngine; using System.Collections;

public class PlayerClone : MonoBehaviour { public AudioClip shoot; public GameObject playerLaser; float projectileSpeed = 5f; float speed = 3f; float fireRate = 0.2f;

 float xmin;
 float xmax;

 float padding = 1f;


 void Start(){
     float distance = transform.position.z - Camera.main.transform.position.z;
     Vector3 leftmost = Camera.main.ViewportToWorldPoint(new Vector3(0,0,distance));
     Vector3 rightmost = Camera.main.ViewportToWorldPoint(new Vector3(1,0,distance));
     xmin = leftmost.x + padding;
     xmax = rightmost.x - padding;
 }

 void Update(){
     if(Input.GetKeyDown(KeyCode.Space)){
         InvokeRepeating ("Fire",0.00001f,fireRate);
     }
     if(Input.GetKeyUp(KeyCode.Space)){
         CancelInvoke("Fire");
     }
     // Moving left or right
     if(Input.GetKey(KeyCode.LeftArrow)){
         transform.position += Vector3.left * speed * Time.deltaTime;
     }else if(Input.GetKey(KeyCode.RightArrow)){
         transform.position += Vector3.right * speed * Time.deltaTime;
     }
     
     // Resctricting the player to the game space
     float newX = Mathf.Clamp(transform.position.x,xmin,xmax);
     transform.position = new Vector3(newX,transform.position.y,transform.position.z);
 }

 void Fire(){
     Vector3 offset = new Vector3(0,1,0);
     GameObject beam = Instantiate(playerLaser, transform.position + offset, Quaternion.identity) as GameObject;
     beam.rigidbody2D.velocity = new Vector3(0,projectileSpeed,0);
     AudioSource.PlayClipAtPoint(shoot,transform.position);
 }

}

screenshot-18.png (28.8 kB)
screenshot-19.png (37.2 kB)
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

25 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How do I resolve, get_isActiveAndEnabled can only be called from the main thread error 1 Answer

Unity 4 error loading page 0 Answers

Button doesn't work on specific part of the game 0 Answers

My 'Score' Variable Is Not Printing To UI Text 1 Answer

WHY !! CountDown not Working inside the IF Conndition !!! 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges