GameObject.transform.position not working properly in Unity - c#

I am making a game in unity and i want to get the position of the player so i use the code for the enemy:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyScript : MonoBehaviour
{
public GameObjetct player;
void Start()
{
Debug.Log(player.transform.position.x);
}
}
I have a spawner and here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnEnemies : MonoBehaviour
{
public GameObject enemy;
float randX;
float randY;
Vector2 whereToSpawn;
public float spawnRate = 2f;
float nextSpawn = 0.0f;
void Update()
{
if (Time.time > nextSpawn)
{
nextSpawn = Time.time + spawnRate;
randX = Random.Range(-6.36f, 6.36f);
randY = Random.Range(-4.99f, 4.99f);
whereToSpawn = new Vector2(randX, randY);
Instantiate (enemy, whereToSpawn, Quaternion.identity);
}
}
}
But when i run it, it always gives me (0, 0, 0). Why do i get 0 and how can i fix it ( get the current position of the player )?

Probably your player variable of enemy is not correctly assigned.
Try to assign the player GameObject variable to your SpawnEnemies object, and let this one assign the player variable to the enemies script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnEnemies : MonoBehaviour
{
public GameObject enemy;
float randX;
float randY;
Vector2 whereToSpawn;
public float spawnRate = 2f;
float nextSpawn = 0.0f;
public GameObject player = null; //Remember to assign this through the editor!
void Update()
{
if (Time.time > nextSpawn)
{
nextSpawn = Time.time + spawnRate;
randX = Random.Range(-6.36f, 6.36f);
randY = Random.Range(-4.99f, 4.99f);
whereToSpawn = new Vector2(randX, randY);
GameObject enemy = Instantiate (enemy, whereToSpawn, Quaternion.identity);
enemy.player = this.player; //here you can assign to each new created enemy your player position on runtime.
}
}
}

Related

All the guns in the game shoot at the same time when I only want the gun that I'm holding to shoot

My problem is that when I'm holding a gun and shoot it, all the other guns on the floor start shooting as well. How do I make it so that only the gun that I'm holding with the mouse can shoot?
You pick up the gun with the mouse left click, and you shoot with right click
My pickup code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PickUp : MonoBehaviour
{
bool Pressed = false;
void OnMouseDown()
{
Pressed = true;
GetComponent<Rigidbody2D>().isKinematic = true;
}
void OnMouseUp()
{
Pressed = false;
GetComponent<Rigidbody2D>().isKinematic = false;
}
void Update()
{
if(Pressed)
{
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = mousePos;
}
}
}
My gun code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : MonoBehaviour{
public Transform firePoint;
public float fireRate = 15f;
public GameObject bulletPrefab;
public Transform MuzzleFlashPrefab;
private float nextTimeToFire = 0f;
void Update() {
if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire)
{
nextTimeToFire = Time.time + 1f/fireRate;
Shoot();
}
}
void Shoot ()
{
Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Transform clone = Instantiate (MuzzleFlashPrefab, firePoint.position, firePoint.rotation) as Transform;
clone.parent = firePoint;
float size = Random.Range (0.02f, 0.025f);
clone.localScale = new Vector3 (size, size, size);
Destroy (clone.gameObject, 0.056f);
}
}
and my bullet code
using System.Collections.Generic;
using UnityEngine;
public class bulet : MonoBehaviour
{
public float speed = 40f;
public Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb.velocity = transform.right * speed;
}
}
Set a flag in your Weapon, something called liked pickedUp, and toggle it when the weapon is picked up/dropped. Then in your Weapon's Update function, check if you should process Inputs for that weapon based on its picked up state. If its not picked up, there is no need to check if it should fire a bullet or not.

Trying to create a random Vector3 in Unity

I am trying to make a random Vector3, but Unity is giving me this error: UnityException: Range is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehavior 'particleMover'.
This is my code:
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using UnityEngine;
public class particleMover : MonoBehaviour
{
public float moveSpeed;
public float temperature;
public Rigidbody rb;
public Transform tf;
static private float[] directions;
// Start is called before the first frame
void Start()
{
System.Random rnd = new System.Random();
float[] directions = { rnd.Next(1, 360), rnd.Next(1, 360), rnd.Next(1, 360) };
}
// Update is called once per frame
void Update()
{
Vector3 direction = new Vector3(directions[0], directions[1], directions[2]);
direction = moveSpeed * direction;
rb.MovePosition(rb.position + direction);
}
}
Vector3 direction = Random.insideUnitSphere;
And you used (1, 360) and it seems you are confusing direction with rotation.
Vector3(x, y, z) - x, y, z are position values, not angles.
In addition, you need to use Time.deltaTime
direction = moveSpeed * direction * Time.deltaTime;
More info: https://docs.unity3d.com/ScriptReference/Time-deltaTime.html
Updated answer:
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using UnityEngine;
public class particleMover : MonoBehaviour
{
public float moveSpeed;
public float temperature;
public Rigidbody rb;
public Transform tf;
private Vector3 direction = Vector3.zero;
void Start()
{
direction = Random.insideUnitSphere;
}
void Update()
{
rf.position += direction * moveSpeed * Time.deltaTime;
// If this script is attached to tf object
// transform.position += direction * moveSpeed * Time.deltaTime;
}
}

Is there a method to stop a player when I stop touching a virtual joystick?

I'm new to unity and I'm trying to make an isometric 3d game, but I have some problem, I would like that the player stops moving when I stop using the virtual joystick. Here's my 2 scripts for movement. The first one is in the virtual joystick to make it move and the second one is in the player and make it move in the direction of the joystick.
Joystick script:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
public class VirtualJoystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
{
private Image bgImg;
private Image joystickImg;
private Vector3 inputVector;
private void Start()
{
bgImg = GetComponent<Image>();
joystickImg = transform.GetChild(0).GetComponent<Image>();
}
public virtual void OnDrag(PointerEventData ped)
{
Vector2 pos;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(bgImg.rectTransform, ped.position, ped.pressEventCamera, out pos))
{
pos.x = (pos.x / bgImg.rectTransform.sizeDelta.x);
pos.y = (pos.y / bgImg.rectTransform.sizeDelta.x);
inputVector = new Vector3(pos.x * 2 + 1, 0, pos.y * 2 - 1);
inputVector = (inputVector.magnitude > 1.0f) ? inputVector.normalized : inputVector;
// Move joystickImg
joystickImg.rectTransform.anchoredPosition =
new Vector3(inputVector.x * bgImg.rectTransform.sizeDelta.x / 3
, inputVector.z * (bgImg.rectTransform.sizeDelta.y / 3));
}
}
public virtual void OnPointerDown(PointerEventData ped)
{
OnDrag(ped);
}
public virtual void OnPointerUp(PointerEventData ped)
{
inputVector = Vector3.zero;
joystickImg.rectTransform.anchoredPosition = Vector3.zero;
}
public float Horizontal()
{
if (inputVector.x != 0)
return inputVector.x;
else
return Input.GetAxis("Horizontal");
}
public float Vertical()
{
if (inputVector.x != 0)
return inputVector.z;
else
return Input.GetAxis("Vertical");
}
}
Player Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
public float moveSpeed = 20f;
public VirtualJoystick moveJoystick;
private void Update()
{
Vector3 dir = Vector3.zero;
dir.x = moveJoystick.Horizontal();
dir.z = moveJoystick.Vertical();
GetComponent<Rigidbody>().AddForce(dir * moveSpeed);
}
}
For stopping the player when you let go of the virtual joystick, we can tell the player's rigidbody to sleep. This will make the player halt until another force is added to it.
Update your Player script to the following:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
public float moveSpeed = 20f;
public VirtualJoystick moveJoystick;
public Rigidbody rb;
private Vector3 dir = Vector3.zero;
private bool wasMoving = false;
private void Update()
{
dir.x = moveJoystick.Horizontal();
dir.z = moveJoystick.Vertical();
if (dir.magnitude > 0)
{
wasMoving = true;
}
}
private void FixedUpdate()
{
if (wasMoving && dir.magnitude == 0f)
{
wasMoving = false;
rb.Sleep();
}
rb.AddForce(dir * moveSpeed);
}
}
It's also a good idea to store the Rigidbody as a variable so you don't recompute it every update. Be sure to drag it into the script from the inspector.

Shoot bullet to direction of last player position

I am trying to code a drone that is shooting a laser-bullet to the last position of the player. The bullet should also rotate to the players position.
I have following script, but it is not shooting for some reason.
using System.Collections.Generic;
using UnityEngine;
public class DroneShoot: MonoBehaviour
{
public Transform bulletspawn;
public Rigidbody2D bulletPrefab;
public float bulletSpeed = 750;
public float bulletDelay;
private Transform player;
private Rigidbody2D clone;
// Use this for initialization
void Start()
{
player = GameObject.FindGameObjectWithTag("spieler").GetComponent<Transform>();
StartCoroutine(Attack());
}
IEnumerator Attack()
{
yield return new WaitForSeconds(bulletDelay);
if (Vector3.Distance(player.transform.position, bulletspawn.transform.position) < 20)
{
Quaternion rotation = Quaternion.LookRotation(player.transform.position, bulletspawn.transform.position);
bulletspawn.rotation = rotation;
clone = Instantiate(bulletPrefab, bulletspawn.position, bulletspawn.rotation);
clone.AddForce(bulletspawn.transform.right * bulletSpeed);
StartCoroutine(Attack());
}
}
}
It looks like it will only try to fire again if it is able to fire the first time because StartCoroutine is inside the distance check.
I think it should keep trying to shoot forever.
IEnumerator Attack()
{
while(true){
yield return new WaitForSeconds(shootDelay);
if (Vector3.Distance(player.transform.position, bulletspawn.transform.position) < 20)
{
Quaternion rotation = Quaternion.LookRotation(player.transform.position);
bulletspawn.rotation = rotation;
clone = Instantiate(bulletPrefab, bulletspawn.position, bulletspawn.rotation);
clone.AddForce(bulletspawn.transform.right * bulletSpeed);
}
}
}
I have a solution.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DroneShoot: MonoBehaviour
{
public Transform bulletspawn;
public Rigidbody2D bulletPrefab;
public float bulletSpeed = 750;
public float bulletDelay;
private Transform player;
private Rigidbody2D clone;
// Use this for initialization
void Start()
{
player = GameObject.FindGameObjectWithTag("spieler").GetComponent<Transform>();
StartCoroutine(Attack());
}
IEnumerator Attack()
{
yield return new WaitForSeconds(bulletDelay);
if (Vector3.Distance(player.transform.position, bulletspawn.transform.position) < 20)
{
Vector3 difference = player.position - bulletspawn.position;
float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
bulletspawn.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ);
clone = Instantiate(bulletPrefab, bulletspawn.position, bulletspawn.rotation);
clone.AddForce(bulletspawn.transform.right * bulletSpeed);
StartCoroutine(Attack());
}
}
}

Why In Unity5, does my triggercollider2D only sense collisions with certain objects and not others?

I'm using a trigger collider (a circleCollider2D with is trigger checked) but it's only sensing collisions with certain objects.
here's the script on the trigger:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Scoring : MonoBehaviour {
public updateScore updateScore;
Transform earth;
// Use this for initialization
void Start () {
earth = GetComponent<Transform>();
}
void OnTriggerExit2D(Collider2D other)
{
Debug.Log("other collider " + other);
updateScore.score++;
}
}
it's sensing this object:
it's a 2D meteor object that has a rigidbody2D and a circleCollider2D on it.
it has this script attached:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CometMovement : MonoBehaviour {
public float speed = 0.5f;
Rigidbody2D rb;
Vector2 direction;
// Use this for initialization
void Start () {
direction = new Vector2(Random.Range(10.0f, -10.0f), Random.Range(10.0f, -10.0f));
rb = GetComponent<Rigidbody2D>();
rb.AddForce(direction * speed);
}
}
But it's not sensing this below object. I need it to sense this below object:
It's an earth object with a rigidbody2d and CircleCollider2D, pretty much the same as the meteor object.
it has this script attached:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class EarthController : MonoBehaviour {
public float force = 0.5f;
Rigidbody2D rb;
Vector2 direction;
Transform transform;
// Use this for initialization
void Start () {
direction = new Vector2(0, 4);
transform = GetComponent<Transform>();
rb = GetComponent<Rigidbody2D>();
rb.isKinematic = false;
}
// void OnCollisionEnter2D(Collision2D coll) {
// SceneManager.LoadScene("Level 01");
//
// }
// Update is called once per frame
void Update () {
if(Input.GetButton("Fire1")){
rb.isKinematic = false;
if(transform.position.x <= 0 && transform.position.y <= 4){
direction = new Vector2(0, -4);
} else {
direction = new Vector2(0, 4);
}
rb.AddForce(direction * force);
Debug.Log("going this fast: " + rb.inertia);
} else {
rb.isKinematic = true;
rb.velocity = Vector2.zero;
}
}
}
According to the documentation :
If isKinematic is enabled, Forces, collisions or joints will not affect the rigidbody anymore
if(Input.GetButton("Fire1")){
rb.isKinematic = false;
// ...
} else {
rb.isKinematic = true;
}
Also, check your Physics parameters ?
Make sure both of your colliders are not triggers. Not sure about this one.

Categories

Resources