CrossplatformInput Joystick is not working in Unity - c#

I have connected a joystick from the standard assets library from the unity store, but the input is not being read. The car can be controlled by the arrow keys,but the joystick is not working.
here is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
public class rearwheeldrive : MonoBehaviour
{
public float maxAngle = 30;
public float maxTorque = 300;
public WheelCollider[] wheelArray;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float angle = maxAngle * CrossPlatformInputManager.GetAxis("Horizontal");
float torque = maxTorque * CrossPlatformInputManager.GetAxis("Vertical");
wheelArray[0].steerAngle = angle;
wheelArray[1].steerAngle = angle;
wheelArray[2].motorTorque = torque;
wheelArray[3].motorTorque = torque;
foreach (WheelCollider wheelcollider in wheelArray)
{
Vector3 P;
Quaternion Q;
wheelcollider.GetWorldPose(out P, out Q);
Transform wheelshape = wheelcollider.transform.GetChild(0);
wheelshape.position = P;
wheelshape.rotation = Q;
}
}
}
Even after changing maxAngle * Input.GetAxis("Horizontal"); to maxAngle * CrossPlatformInputManager.GetAxis("Horizontal"); it takes the arrow key input whilst the joystick is not working.
Code Of Joystick object
using System;
using UnityEngine;
using UnityEngine.EventSystems;
namespace UnityStandardAssets.CrossPlatformInput
{
public class Joystick : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler
{
public enum AxisOption
{
// Options for which axes to use
Both, // Use both
OnlyHorizontal, // Only horizontal
OnlyVertical // Only vertical
}
public int MovementRange = 100;
public AxisOption axesToUse = AxisOption.Both; // The options for the axes that the still will use
public string horizontalAxisName = "Horizontal"; // The name given to the horizontal axis for the cross platform input
public string verticalAxisName = "Vertical"; // The name given to the vertical axis for the cross platform input
Vector3 m_StartPos;
bool m_UseX; // Toggle for using the x axis
bool m_UseY; // Toggle for using the Y axis
CrossPlatformInputManager.VirtualAxis m_HorizontalVirtualAxis; // Reference to the joystick in the cross platform input
CrossPlatformInputManager.VirtualAxis m_VerticalVirtualAxis; // Reference to the joystick in the cross platform input
void OnEnable()
{
CreateVirtualAxes();
}
void Start()
{
m_StartPos = transform.position;
}
void UpdateVirtualAxes(Vector3 value)
{
var delta = m_StartPos - value;
delta.y = -delta.y;
delta /= MovementRange;
if (m_UseX)
{
m_HorizontalVirtualAxis.Update(-delta.x);
}
if (m_UseY)
{
m_VerticalVirtualAxis.Update(delta.y);
}
}
void CreateVirtualAxes()
{
// set axes to use
m_UseX = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyHorizontal);
m_UseY = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyVertical);
// create new axes based on axes to use
if (m_UseX)
{
m_HorizontalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(horizontalAxisName);
CrossPlatformInputManager.RegisterVirtualAxis(m_HorizontalVirtualAxis);
}
if (m_UseY)
{
m_VerticalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(verticalAxisName);
CrossPlatformInputManager.RegisterVirtualAxis(m_VerticalVirtualAxis);
}
}
public void OnDrag(PointerEventData data)
{
Vector3 newPos = Vector3.zero;
if (m_UseX)
{
int delta = (int)(data.position.x - m_StartPos.x);
delta = Mathf.Clamp(delta, - MovementRange, MovementRange);
newPos.x = delta;
}
if (m_UseY)
{
int delta = (int)(data.position.y - m_StartPos.y);
delta = Mathf.Clamp(delta, -MovementRange, MovementRange);
newPos.y = delta;
}
transform.position = new Vector3(m_StartPos.x + newPos.x, m_StartPos.y + newPos.y, m_StartPos.z + newPos.z);
UpdateVirtualAxes(transform.position);
}
public void OnPointerUp(PointerEventData data)
{
transform.position = m_StartPos;
UpdateVirtualAxes(m_StartPos);
}
public void OnPointerDown(PointerEventData data) { }
void OnDisable()
{
// remove the joysticks from the cross platform input
if (m_UseX)
{
m_HorizontalVirtualAxis.Remove();
}
if (m_UseY)
{
m_VerticalVirtualAxis.Remove();
}
}
}
}

Use it Like :
public Joystick mJoystick;
float angle = maxAngle * mJoystick.Horizontal;
float torque = maxTorque * mJoystick.Vertical;
EDIT : I have used the same asset, works fine using the below settings.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
public class TestScript : MonoBehaviour
{
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
float angle = CrossPlatformInputManager.GetAxis("Horizontal");
float torque = CrossPlatformInputManager.GetAxis("Vertical");
print("Angle : " + angle + " , Torque : " + torque);
}
}

Related

How can I change the moving objects speed at runtime?

The manager script
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class DronesManager : MonoBehaviour
{
public GameObject target;
public float movementSpeed;
public float launchTime;
public Transform dronesUnchild;
private List<GameObject> drones = new List<GameObject>();
private float currentDroneSpeed;
private void Awake()
{
currentDroneSpeed = movementSpeed;
}
// Start is called before the first frame update
void Start()
{
target = GameObject.Find("Base");
drones = GameObject.FindGameObjectsWithTag("Drone").ToList();
StartCoroutine(MoveDrone());
}
// Update is called once per frame
void Update()
{
if(currentDroneSpeed != movementSpeed)
{
for(int i = 0; i < drones.Count; i++)
{
var droneControl = drones[i].GetComponent<DroneControl>();
droneControl.movingSpeed = movementSpeed;
}
currentDroneSpeed = movementSpeed;
}
}
private IEnumerator MoveDrone()
{
// same as you did:
drones = GameObject.FindGameObjectsWithTag("Drone").ToList();
foreach(var drone in drones)
{
drone.GetComponent<DroneControl>().target = target.transform;
}
while (drones.Count > 0)
{
// pick one at random, get it
int index = Random.Range(0, drones.Count);
var drone = drones[index];
// remove it from list
drones.RemoveAt(index);
// TODO: might want to check/guard if drone == null ... this guards against it
// being Destroy()ed and yet still lying around in our list marked as "dead"
// simplified your get-component-and-go-if-not-already-going code here
var droneControl = drone.GetComponent<DroneControl>();
if (droneControl.go == false)
{
droneControl.movingSpeed = movementSpeed;
droneControl.go = true;
drone.transform.parent = dronesUnchild;
}
// wait
yield return new WaitForSeconds(launchTime);
}
}
}
I tried to add this part in the Update
void Update()
{
if(currentDroneSpeed != movementSpeed)
{
for(int i = 0; i < drones.Count; i++)
{
var droneControl = drones[i].GetComponent<DroneControl>();
droneControl.movingSpeed = movementSpeed;
}
currentDroneSpeed = movementSpeed;
}
}
and this script is attached to each moving object
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DroneControl : MonoBehaviour
{
public Transform target;
public float turnSpeed = .01f;
Quaternion rotGoal;
Vector3 direction;
public float movingSpeed;
public bool go = false;
private bool waitBeforeRotate = false;
private bool startRotating = false;
#region AddedCode
public float targetRange = 1.0f;
private bool IsTargetReached(Vector3 dronePos, Vector3 targetPos)
{
var distance = Vector3.Distance(dronePos, targetPos);
return distance < targetRange;
}
#endregion AddedCode
// Update is called once per frame
void Update()
{
// next line is modified to incorporate the range check
if (go && !IsTargetReached(transform.position, target.position))
{
transform.position += transform.forward * movingSpeed * Time.deltaTime;
if (waitBeforeRotate == false)
{
StartCoroutine(StartRotating());
waitBeforeRotate = true;
}
if (startRotating)
{
direction = (target.position - transform.position).normalized;
rotGoal = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, rotGoal, turnSpeed);
}
}
}
IEnumerator StartRotating()
{
yield return new WaitForSeconds(3f);
startRotating = true;
}
}
but it's never change the speed of moving objects.
if the speed of each moving object in the editor start is 5 for example and in the manager script I change the speed to 100 the speed of each object is still 5.
Maybe this is happening because after picking a random drone in IEnumerator you instantly remove it from the list?
So in Update() you set a speed for all drones, except the ones that are already moving.

Blend tree in animator controller how can I change between animations smooth?

This is a screenshot of the blend tree. The top first animation is idle and on the left side bottom there is a Forward and I added also a Forward parameter. This Forward controls the player's movement speed.
and with this script attached to the player, I'm controlling the Forward parameter and slow down the player movement.
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class PlayerSpaceshipAreaColliding : MonoBehaviour
{
public float rotationSpeed =250;
public float movingSpeed;
public float secondsToRotate;
public GameObject uiSceneText;
public TextMeshProUGUI textMeshProUGUI;
private float timeElapsed = 0;
private float lerpDuration = 3;
private float startValue = 1;
private float endValue = 0;
private float valueToLerp = 0;
private Animator playerAnimator;
private bool exitSpaceShipSurroundingArea = false;
private bool slowd = true;
private bool startRotatingBack = false;
private bool displayText = true;
private float desiredRot;
public float damping = 10;
private Rigidbody playerRigidbody;
// Start is called before the first frame update
void Start()
{
playerAnimator = GetComponent<Animator>();
playerRigidbody = GetComponent<Rigidbody>();
desiredRot = transform.eulerAngles.y;
}
// Update is called once per frame
void Update()
{
if (exitSpaceShipSurroundingArea)
{
if (slowd)
SlowDown();
if (playerAnimator.GetFloat("Forward") == 0)
{
slowd = false;
LockController.PlayerLockState(false);
if (displayText)
{
uiSceneText.SetActive(true);
if (textMeshProUGUI.text != "")
textMeshProUGUI.text = "";
textMeshProUGUI.text = "I can see something very far in the distance, but it's too long to walk by foot.";
StartCoroutine(UITextWait());
displayText = false;
}
}
}
}
IEnumerator UITextWait()
{
yield return new WaitForSeconds(5f);
textMeshProUGUI.text = "";
uiSceneText.SetActive(false);
startRotatingBack = true;
}
private void OnTriggerEnter(Collider other)
{
if (other.name == "CrashLandedShipUpDown")
{
exitSpaceShipSurroundingArea = false;
Debug.Log("Entered Spaceship Area !");
}
}
private void OnTriggerExit(Collider other)
{
if (other.name == "CrashLandedShipUpDown")
{
exitSpaceShipSurroundingArea = true;
Debug.Log("Exited Spaceship Area !");
}
}
private void SlowDown()
{
if (timeElapsed < lerpDuration)
{
valueToLerp = Mathf.Lerp(startValue, endValue, timeElapsed / lerpDuration);
playerAnimator.SetFloat("Forward", valueToLerp);
timeElapsed += Time.deltaTime;
}
playerAnimator.SetFloat("Forward", valueToLerp);
valueToLerp = 0;
}
}
The problem is when Forward gets to value 0 and the player stops its kind of jumping to the idle animation in the blend tree and not smooth changing to it.
The value of the idle animation (Changes animation speed) in the inspector I marked with a red circle was 1 like the rest but because it was kind of jumping to the idle I changed it to 0.5 but now the whole idle animation is playing too slow like in slow motion.
I'm not sure why it's jumping the change from the slow down to the idle is looks like it's cutting jumping to it and not smoothly change to the idle animation ?
The solution that worked for me.
Inside the script ThirdPersonUserControl instead of disabling the whole script like I'm doing in the line LockController.PlayerLockState(false); I just added a public static bool and by setting the bool to true it will avoid using the input's in the script :
The new bool variable is name stop :
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
namespace UnityStandardAssets.Characters.ThirdPerson
{
[RequireComponent(typeof (ThirdPersonCharacter))]
public class ThirdPersonUserControl : MonoBehaviour
{
private ThirdPersonCharacter m_Character; // A reference to the ThirdPersonCharacter on the object
private Transform m_Cam; // A reference to the main camera in the scenes transform
private Vector3 m_CamForward; // The current forward direction of the camera
private Vector3 m_Move;
private bool m_Jump; // the world-relative desired move direction, calculated from the camForward and user input.
public static bool stop = false;
private void Start()
{
// get the transform of the main camera
if (Camera.main != null)
{
m_Cam = Camera.main.transform;
}
else
{
Debug.LogWarning(
"Warning: no main camera found. Third person character needs a Camera tagged \"MainCamera\", for camera-relative controls.", gameObject);
// we use self-relative controls in this case, which probably isn't what the user wants, but hey, we warned them!
}
// get the third person character ( this should never be null due to require component )
m_Character = GetComponent<ThirdPersonCharacter>();
}
private void Update()
{
if (!m_Jump)
{
m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}
}
// Fixed update is called in sync with physics
private void FixedUpdate()
{
if (stop == false)
{
// read inputs
float h = CrossPlatformInputManager.GetAxis("Horizontal");
float v = CrossPlatformInputManager.GetAxis("Vertical");
bool crouch = Input.GetKey(KeyCode.C);
// calculate move direction to pass to character
if (m_Cam != null)
{
// calculate camera relative direction to move:
m_CamForward = Vector3.Scale(m_Cam.forward, new Vector3(1, 0, 1)).normalized;
m_Move = v * m_CamForward + h * m_Cam.right;
}
else
{
// we use world-relative directions in the case of no main camera
m_Move = v * Vector3.forward + h * Vector3.right;
}
#if !MOBILE_INPUT
// walk speed multiplier
if (Input.GetKey(KeyCode.LeftShift)) m_Move *= 0.5f;
#endif
// pass all parameters to the character control script
m_Character.Move(m_Move, crouch, m_Jump);
m_Jump = false;
}
}
}
}
Then in my script, the player is slow down stop and then not moving and it's changing smoothly to the idle animation because it's doing it already in the blend tree the problem is not with the blend tree but was with the way I tried to lock the player from moving.
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityStandardAssets.Characters.ThirdPerson;
public class PlayerSpaceshipAreaColliding : MonoBehaviour
{
public float rotationSpeed =250;
public float movingSpeed;
public float secondsToRotate;
public GameObject uiSceneText;
public TextMeshProUGUI textMeshProUGUI;
private float timeElapsed = 0;
private float lerpDuration = 3;
private float startValue = 1;
private float endValue = 0;
private float valueToLerp = 0;
private Animator playerAnimator;
private bool exitSpaceShipSurroundingArea = false;
private bool slowd = true;
private bool startRotatingBack = false;
private bool displayText = true;
public float damping = 10;
private Quaternion playerRotation;
// Start is called before the first frame update
void Start()
{
playerAnimator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (exitSpaceShipSurroundingArea)
{
if (slowd)
SlowDown();
if (playerAnimator.GetFloat("Forward") == 0)
{
slowd = false;
ThirdPersonUserControl.stop = true;
if (displayText)
{
uiSceneText.SetActive(true);
if (textMeshProUGUI.text != "")
textMeshProUGUI.text = "";
textMeshProUGUI.text = "I can see something very far in the distance, but it's too long to walk by foot.";
StartCoroutine(UITextWait());
displayText = false;
}
}
if (startRotatingBack)
{
transform.rotation = Quaternion.RotateTowards(transform.rotation, playerRotation, rotationSpeed * Time.deltaTime);
}
}
}
IEnumerator UITextWait()
{
yield return new WaitForSeconds(5f);
textMeshProUGUI.text = "";
uiSceneText.SetActive(false);
startRotatingBack = true;
}
private void OnTriggerEnter(Collider other)
{
if (other.name == "CrashLandedShipUpDown")
{
exitSpaceShipSurroundingArea = false;
Debug.Log("Entered Spaceship Area !");
}
}
private void OnTriggerExit(Collider other)
{
if (other.name == "CrashLandedShipUpDown")
{
playerRotation = transform.rotation;
exitSpaceShipSurroundingArea = true;
Debug.Log("Exited Spaceship Area !");
}
}
private void SlowDown()
{
if (timeElapsed < lerpDuration)
{
valueToLerp = Mathf.Lerp(startValue, endValue, timeElapsed / lerpDuration);
playerAnimator.SetFloat("Forward", valueToLerp);
timeElapsed += Time.deltaTime;
}
playerAnimator.SetFloat("Forward", valueToLerp);
valueToLerp = 0;
}
}

Why do objects move apart, although they should move toward each other?

I'm tired...
I'm tried to make a simple 2d planetary shooter and started from creating my own physic with Newton's law of universal gravitation(something like that), but my code isn't working - bodies moves from each other, while they Colliders is colliding, and I don't know why.(even inertia)
So, I've tried to capy and paste code from another StackOverflow, but its not working too. Requesting some help!
https://imgur.com/qvnLxSk
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CircleCollider2D), typeof(CircleCollider2D))]
public class MassEffect : MonoBehaviour
{
//public GameObject player;
private float gRadius = 5f;
public float rotSpeed = 0.5f;
public float gravitation = 50f;
private HashSet<Rigidbody2D> affectedBodies = new HashSet<Rigidbody2D>();
private Rigidbody2D componentRigidbody;
private CircleCollider2D gTrigger;
private void Start()
{
componentRigidbody = GetComponent<Rigidbody2D>();
gTrigger = GetComponents<CircleCollider2D>()[1];
gTrigger.isTrigger = true;
gTrigger.radius = gRadius / transform.localScale.x;
}
private void OnTriggerEnter2D(Collider2D other)
{
var rbInRadius = other.GetComponent<Rigidbody2D>();
if (rbInRadius != null)
{
affectedBodies.Add(rbInRadius);
}
}
private void OnTriggerExit2D(Collider2D other)
{
var rbInRadius = other.GetComponent<Rigidbody2D>();
if (rbInRadius != null)
{
affectedBodies.Remove(rbInRadius);
}
}
private void FixedUpdate()
{
transform.Rotate(Vector3.forward * rotSpeed);
foreach (var objectInVicinity in affectedBodies)
{
if (objectInVicinity == null)
{
affectedBodies.Remove(objectInVicinity);
break;
}
float dist = Vector2.Distance(transform.position, objectInVicinity.transform.position);
float gravitationFactor = 1 - dist / gRadius;
Vector2 force = (transform.position - objectInVicinity.transform.position).normalized * gravitation * gravitationFactor;
objectInVicinity.AddForce(force);
}
}
void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, gRadius);
}
}

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.

Unity C# Simple Multiplayer game ending

How can I edit the c# code to show that player 1 or 2 won when the other player dies. And show the dead player that they lost?
PlayerController Script
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
namespace S3
{
public class PlayerController : NetworkBehaviour {
public GameObject bulletPrefab;
public Transform bulletSpawn;
// Update is called once per frame
void Update ()
{
if (!isLocalPlayer) {
return;
}
float x = Input.GetAxis ("Horizontal") * Time.deltaTime * 150.0f;
float z = Input.GetAxis ("Vertical") * Time.deltaTime * 3.0f;
transform.Rotate (0, x, 0);
transform.Translate (0, 0, z);
if (Input.GetKeyDown (KeyCode.Space))
{
CmdFire();
}
}
[Command]
void CmdFire()
{
GameObject bullet = (GameObject) Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);
bullet.GetComponent<Rigidbody> ().velocity = bullet.transform.forward * 6.0f;
NetworkServer.Spawn(bullet);
Destroy (bullet, 2);
}
public override void OnStartLocalPlayer()
{
GetComponent<MeshRenderer> ().material.color = Color.blue;
}
}
}
Health Script
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
namespace S3
{
public class Health : NetworkBehaviour {
public const int maxHealth = 100;
[SyncVar (hook = "OnChangeHealth")]public int currentHealth = maxHealth;
public RectTransform healthbar;
public void TakeDamage(int amount)
{
if (!isServer)
{
return;
}
currentHealth -= amount;
if (currentHealth <= 0)
{
currentHealth = maxHealth;
RpcRespawn();
}
}
void OnChangeHealth(int health)
{
healthbar.sizeDelta = new Vector2(health * 2, healthbar.sizeDelta.y);
}
[ClientRpc]
void RpcRespawn()
{
if(isLocalPlayer)
{
transform.position = Vector3.zero;
}
}
}
}
This is the codeaspğlasdlişsadlşisadlşiadsilşdslaişdlasişlişdsacdl işsadilşaLDİŞaslişÖDASİÖŞLDÖİLSAŞDöliasödilascöildaiölşsdöiaşsdöilasödilasiöldasöildasöildöilasdöilaöildöildasöildaöilsdöilasdölasdöliasölidasöildsaöildsöiladiösladöilsadöilsadöilasdiölsadiölsaöidlsaöildsöidiösladiölsadiölsadöilasöild
You can send a Command to the server with netID of the player who have won and check in RPC if the netID matches.
If netID matches for the local player then, he is the winner. Otherwise, he loses. Haven't tested the code below but should work:
[Command]
public void CmdGameWon()
{
RpcGameEnd(this.netId);
}
[ClientRpc]
public void RpcGameEnd(NetworkInstanceId nid)
{
if(this.isLocalPlayer && this.netId==nid){
//Process win here
}else{
//Process lose here
}
}

Categories

Resources