I'm making a 3d isometric game and I'm trying to shoot things from player to a direction taked with a joystick and I would like that it shoots when I release the joystick. You can easly search Brawl Stars video to understand better what I mean. The first script is of the joystick and the second for the shoot(I putted it inside the player). It now gives me this error: the object you want to instantiate is null.
Joystick's script :
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
public class rightjoystick : 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.y);
inputVector = new Vector3(pos.x * 2, 0, pos.y * 2);
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.z != 0)
return inputVector.z;
else
return Input.GetAxis("Vertical");
}
}
shooting script :
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class shoot : MonoBehaviour
{
public Rigidbody proiettile;
public float launchForce = 70f;
public rightjoystick moveJoystick;
private Vector3 dir = Vector3.zero;
public void Update()
{
dir.x = moveJoystick.Horizontal();
dir.z = moveJoystick.Vertical();
}
private void FixedUpdate()
{
var projectileInstance = Instantiate(proiettile);
projectileInstance.AddForce(dir * launchForce);
}
}
I solved with this:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
public class shoot : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
{
private Image bgImg;
private Image joystickImg;
private Vector3 inputVector;
public Rigidbody proiettile;
private Vector3 dir = Vector3.zero;
private Vector3 newpos;
public float launchForce;
public Rigidbody Player;
private Rigidbody clone;
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.y);
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)
{
dir.x = Horizontal();
dir.z = Vertical();
newpos = dir * (launchForce);
clone = Instantiate(proiettile, Player.transform.position, Player.transform.rotation);
clone.transform.position=Vector3.MoveTowards(Player.transform.position,newpos,10f);
// joystick come back to start position
inputVector = Vector3.zero;
joystickImg.rectTransform.anchoredPosition = Vector3.zero;
clone.timeoutDestructor = 5;
}
public float Horizontal()
{
if (inputVector.x != 0)
return inputVector.x;
else
return Input.GetAxis("Horizontal");
}
public float Vertical()
{
if (inputVector.z != 0)
return inputVector.z;
else
return Input.GetAxis("Vertical");
}
}
Related
I want to make a damage indicator for my online game, but there is an error in my code, can you check it?
Script 1
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class di_system : MonoBehaviour
{
[Header("References")]
[SerializeField] private DamageIndicator indicatorPrefab = null;
[SerializeField] private RectTransform holder = null;
[SerializeField] private Camera camera = null;
[SerializeField] private Transform player = null;
private Dictionary<Transform, DamageIndicator> Indicators = new Dictionary<Transform, DamageIndicator>();
#region Delegates
public static Action<Transform> CreateIndicator = delegate { };
public static Func<Transform, bool> CheckIfObjectInSight = null;
#endregion
private void OnEnable()
{
CreateIndicator += Create;
CheckIfObjectInSight += InSight;
}
private void OnDisable()
{
CreateIndicator -= Create;
CheckIfObjectInSight -= InSight;
}
void Create(Transform target)
{
if (Indicators.ContainsKey(target))
{
Indicators[target].Restart();
return;
}
DamageIndicator newIndicator = Instantiate(indicatorPrefab, holder);
newIndicator.Register(target, player, new Action(() => { Indicators.Remove(target); }));
Indicators.Add(target, newIndicator);
}
bool InSight(Transform t)
{
Vector3 screenPoint = camera.WorldToViewportPoint(t.position);
return screenPoint.z > 0 && screenPoint.x > 0 && screenPoint.x < 1 && screenPoint.y > 0 && screenPoint.y < 1;
}
}
Script 2
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;
public class Health : MonoBehaviour
{
public float health;
public float maxHealth;
public float HealSpeed;
public Image healthBar;
float lerpSpeed;
public bool heal;
public PhotonView PV;
public Manager manager;
public bool dead;
public bool spawnShield;
public float spawnShieldTime;
public float SST;
public GameObject SSUI;
public GameObject SSUI2;
public Text healthText;
// Start is called before the first frame update
void Start()
{
manager = GameObject.FindWithTag("Scripts").GetComponent<Manager>();
spawnShield = true;
SST = spawnShieldTime;
}
// Update is called once per frame
void Update()
{
healthText.text = health.ToString("0");
if (Input.anyKey && spawnShield)
{
StartCoroutine(waitt());
}
if (spawnShield)
{
health = maxHealth;
SST -= 1f * Time.deltaTime;
SSUI.SetActive(true);
SSUI2.SetActive(true);
SSUI2.GetComponent<Text>().text = SST.ToString("0.0");
}
else
{
SSUI.SetActive(false);
SSUI2.SetActive(false);
}
if (SST <= 0)
{
PV.RPC("SpawnShieldOff", RpcTarget.All);
}
}
[PunRPC]
public void Damage(float damage)
{
Register();
health -= damage;
if (PV.IsMine)
{
if (health <= 0)
{
Die();
}
}
if (health <= 0)
{
dead = true;
}
}
public void Die()
{
manager.deaths++;
manager.cooldown();
manager.Alive = false;
PhotonNetwork.Destroy(gameObject);
}
[PunRPC]
public void SpawnShieldOff()
{
spawnShield = false;
}
void Register()
{
if (!di_system.CheckIfObjectInSight(this.transform))
{
di_system.CreateIndicator(this.transform);
}
}
}
I want to make damage indicators for my multiplayer game. Can you help me?
I've been trying to solve this problem for a long time but I couldn't find anything.
No errors in the code, but it shows the rotation of the damaged player instead of the rotation of the damaging player
So i am new to Mirror and i made this to learn a bit,it changes name of the host normally but when i try it on a client he just disconnects,and without any errors.I have setup many debug.log statements to see where is the problem and it seems that is not even executing as a client,it just stops before it was called.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
using TMPro;
using System;`
public class PlayerMovement : NetworkBehaviour
{
public float speed;
float x, y;
Rigidbody2D rb;
Animator animator;
public TMP_InputField tmpf;
public TMP_Text nameText;
[SyncVar(hook = nameof(DisplayName))]
public string _name = "00";
void DisplayName(string oldName, string newName)
{
nameText.text = newName;
}
void Start()
{
if (!isLocalPlayer) return;
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
tmpf = GameObject.Find("NameIF").GetComponent<TMP_InputField>();
//tmpf.onValueChanged.AddListener(delegate { CmdChangeName(); });
}
void Update()
{
if (!isLocalPlayer) return;
x = Input.GetAxis("Horizontal");
y = Input.GetAxis("Vertical");
rb.velocity = new Vector2(x * speed, y * speed);
animator.SetFloat("horizontal", x);
animator.SetFloat("vertical", y);
if (Input.GetKeyDown(KeyCode.KeypadEnter))
{
CmdChangeName();
}
}
[Command]
public void CmdChangeName()
{
_name = tmpf.text;
}
How to fix this,i have client authority checked and i need to use commands if i want hooks and syncVar to work.
The game is working correctly and there arent any other issues apart from the fact that the public fields from the players scripts that are supposed to be filled with game objects from the scene arent filled and im not sure how to do that.
heres an example from one of the scripts: image
and heres what it should look like: image
the joystick area from the second image is from the scene, not an asset: image
here is the code im using:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovePlayer : MonoBehaviour
{
public MovementJoystick movementJoystick;
public int playerSpeed;
private Rigidbody2D rb;
bool facingRight = true;
public Animator animator;
public float interval;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
playerSpeed = 7;
interval = 10;
}
// Update is called once per frame
void FixedUpdate()
{
if (movementJoystick.joystickVec.y != 0)
{
rb.velocity = new Vector2(movementJoystick.joystickVec.x * playerSpeed, movementJoystick.joystickVec.y * playerSpeed);
animator.SetFloat("speed", Mathf.Abs(movementJoystick.joystickVec.x));
}
else
{
rb.velocity = Vector2.zero;
animator.SetFloat("speed", Mathf.Abs(0));
}
if (movementJoystick.joystickVec.x < 0 && !facingRight)
{
Flip();
}
if (movementJoystick.joystickVec.x > 0 && facingRight)
{
Flip();
}
}
void Update()
{
if (playerSpeed == 14 && interval > 0)
{
interval -= Time.deltaTime;
}
else
{
playerSpeed = 7;
interval = 10;
}
}
void Flip()
{
transform.Rotate(0f, 180f, 0f);
facingRight = !facingRight;
}
public void SpeedControl(int newplayerSpeed)
{
playerSpeed = newplayerSpeed;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class MovementJoystick : MonoBehaviour
{
public GameObject joystick;
public GameObject joystickBG;
public Vector2 joystickVec;
private Vector2 joystickTouchPos;
private Vector2 joystickOriginalPos;
private float joystickRadius;
// Start is called before the first frame update
void Start()
{
joystickOriginalPos = joystickBG.transform.position;
joystickRadius = joystickBG.GetComponent<RectTransform>().sizeDelta.y / 2;
}
public void PointerDown()
{
joystick.transform.position = Input.mousePosition;
joystickBG.transform.position = Input.mousePosition;
joystickTouchPos = Input.mousePosition;
}
public void Drag(BaseEventData baseEventData)
{
PointerEventData pointerEventData = baseEventData as PointerEventData;
Vector2 dragPos = pointerEventData.position;
joystickVec = (dragPos - joystickTouchPos).normalized;
float joystickDist = Vector2.Distance(dragPos, joystickTouchPos);
if (joystickDist < joystickRadius)
{
joystick.transform.position = joystickTouchPos + joystickVec * joystickDist;
}
else
{
joystick.transform.position = joystickTouchPos + joystickVec * joystickRadius;
}
}
public void PointerUp()
{
joystickVec = Vector2.zero;
joystick.transform.position = joystickOriginalPos;
joystickBG.transform.position = joystickOriginalPos;
}
}
this is how to instantiate the player using photon servers (what i am using)
public GameObject playerToSpawn;
PhotonNetwork.Instantiate(playerToSpawn.name, spawnPoint.position, Quaternion.identity);
There are also 2 buttons i need you to fix: a Shoot button and a Hit button (those are the names). Here is the code for them:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShootButton : MonoBehaviour
{
//i made this script for the button incase you may
have
needed it
}
Here is the shooting script attached to the player:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Weapon : MonoBehaviour
{
public Transform firePoint;
public GameObject bulletPrefab;
public Button ShootButton;
void Start()
{
ShootButton.onClick.AddListener(ShootButtonTrue);
}
void ShootButtonTrue()
{
Shoot();
}
void Shoot()
{
Instantiate(bulletPrefab, firePoint.position,
firePoint.rotation);
}
}
Here is the hitting script attached to the Hit button
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HitButton : MonoBehaviour
{
}
And here is the Player Combat script using for hitting:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerCombat : MonoBehaviour
{
public Animator animator;
public Button AttackButton;
public Transform attackPoint;
public float attackRange = 0.5f;
public LayerMask enemyLayers;
void Start()
{
AttackButton.onClick.AddListener(AttackButtonTrue);
}
void AttackButtonTrue()
{
Attack();
}
void Attack()
{
animator.SetTrigger("Attack");
Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attackPoint.position, attackRange, enemyLayers);
foreach(Collider2D enemy in hitEnemies)
{
Debug.Log("u hit someone :O");
enemy.GetComponent<Health>().TakeDamage(15);
}
}
void OnDrawGizmosSelected()
{
if (attackPoint == null)
return;
Gizmos.DrawWireSphere(attackPoint.position, attackRange);
}
}
if you need any other pieces of code just ask
thanks in advance, i will mark the answer as an answer if its a good answer
There are multiple ways to achieve this. For example, you can make your joystick singleton and assign that to the player upon spawn. If you have multiple joysticks in the scene, you can group them under the same parent object and make that parent singleton.
Assuming you only have one joystick in the scene, add this into your joystick class:
public static MovementJoystick Instance { get; private set; }
void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(this);
}
else
{
Instance = this;
}
}
In your player class, add this:
void OnEnable()
{
if( movemaneJoystick == null)
{
movementJoystick = MovementJoystick.Instance;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Left : MonoBehaviour
{
public float playerSpeed = 8;
void Update()
{
if (Input.GetKey(KeyCode.W))
{
transform.position = transform.position + new Vector3(0, playerSpeed * Time.deltaTime, 0);
}
if (Input.GetKey(KeyCode.S))
{
transform.position = transform.position + new Vector3(0, -playerSpeed * Time.deltaTime, 0);
}
}
}
How can i do it that the if statements only happen if the gameobject with this script is under y=7 and above y=-7?
This is the code. When I try to add the script to the sprite there's the "primary constructor body not allowed" error.
Inside the code editor there are no alerts.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class weapon : MonoBehaviour {
public GameObject dapo;
public float offset;
public Transform mira;
private float tiempo;
public float inicio;
private void Update()
{
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
if (tiempo <= 0)
{
if (Input.GetMouseButtonDown(0))
{
Instantiate(dapo, mira.position, transform.rotation);
tiempo = inicio;
}
}
else
{
tiempo -= Time.deltaTime;
}
}
}