Unity-Help needed to turn my keyboard and mouse inputs to setup mobile input - unity3d

Hey so I have this input script working fine for the PC just wanted to try mobile input. Can someone help to turn this script to work with mobile? I haven't tried anything yet first time trying mobile input. Just tell me how to set up this script with mobile and UI components.
QWERTYUIOPASDFGHJKLZXCVBNM
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerInput : MonoBehaviour
{
public Vector2 input
{
get
{
Vector2 i = Vector2.zero;
i.x = Input.GetAxis("Horizontal");
i.y = Input.GetAxis("Vertical");
i *= (i.x != 0.0f && i.y != 0.0f) ? .7071f : 1.0f;
return i;
}
}
public Vector2 down
{
get { return _down; }
}
public Vector2 raw
{
get
{
Vector2 i = Vector2.zero;
i.x = Input.GetAxisRaw("Horizontal");
i.y = Input.GetAxisRaw("Vertical");
i *= (i.x != 0.0f && i.y != 0.0f) ? .7071f : 1.0f;
return i;
}
}
public float elevate
{
get
{
return Input.GetAxis("Elevate");
}
}
public bool run
{
get { return Input.GetKey(KeyCode.LeftShift); }
}
public bool crouch
{
get { return Input.GetKeyDown(KeyCode.C); }
}
public bool crouching
{
get { return Input.GetKey(KeyCode.C); }
}
public KeyCode interactKey
{
get { return KeyCode.E; }
}
public bool interact
{
get { return Input.GetKeyDown(interactKey); }
}
public bool reload
{
get { return Input.GetKeyDown(KeyCode.R); }
}
public bool aim
{
get { return Input.GetMouseButtonDown(1); }
}
public bool aiming
{
get { return Input.GetMouseButton(1); }
}
public bool shooting
{
get { return Input.GetMouseButton(0); }
}
public float mouseScroll
{
get { return Input.GetAxisRaw("Mouse ScrollWheel"); }
}
private Vector2 previous;
private Vector2 _down;
private int jumpTimer;
private bool jump;
void Start()
{
jumpTimer = -1;
}
void Update()
{
_down = Vector2.zero;
if (raw.x != previous.x)
{
previous.x = raw.x;
if (previous.x != 0)
_down.x = previous.x;
}
if (raw.y != previous.y)
{
previous.y = raw.y;
if (previous.y != 0)
_down.y = previous.y;
}
}
public void FixedUpdate()
{
if (!Input.GetKey(KeyCode.Space))
{
jump = false;
jumpTimer++;
}
else if (jumpTimer > 0)
jump = true;
}
public bool Jump()
{
return jump;
}
public void ResetJump()
{
jumpTimer = -1;
}
}

You can use the new input system in Unity (I see that you're using an old one). It's a pretty convenient way to make sure that your input are generalizable for a wide range of input controllers.
https://www.youtube.com/watch?v=Yjee_e4fICc

Related

In Unity, line of code keeps blocking video in WebGL?

I want to play a video in WebGL but it keeps blocking my video due to one line of code and I don't know why or how to "repair" it. When clicking on play, only one frame is shown and then it stops. (Entire code below).
The issue is this particular line in my Update function:
if (video.isPlaying)
{
if (!video.isPrepared) return;
videoSlider.value = (float)NTime; //This line here!!!
}
If not commented out, the video wont play, for whatever reason.
NTime, which seems to cause the issue, is:
video.time/ ((ulong)(video.frameCount / video.frameRate)) //video is videoPlayer
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;
using TMPro;
public class SliderVideo : MonoBehaviour
{
[SerializeField] VideoPlayer video;
[SerializeField] Slider videoSlider;
[SerializeField] Slider volumeSlider;
[SerializeField] Button playButton;
[SerializeField] RawImage fullScreenImage;
[SerializeField] RectTransform buttons;
[SerializeField] Vector3 buttonsPos;
Vector3 buttonsPosCache;
[SerializeField] TextMeshProUGUI buttonLanguage;
[SerializeField] GameObject disableButton;
[SerializeField] GameObject videoRectangle;
int cacheWidth, cacheHeight;
float videoWidth, videoHeight;
float videoWidthCache, videoHeightCache;
double videoTimeCache;
bool fullScreen;
float timerMouse;
public bool languageChange = false;
public string videoFileName;
public string videoFileNameEN;
public string videoFileNameDE;
//Start
private void Start()
{
playButton.image.sprite = Resources.LoadAll<Sprite>("icons")[25];
videoRectangle.SetActive(false);
videoHeight = fullScreenImage.gameObject.GetComponent<RectTransform>().sizeDelta.y;
videoWidth = fullScreenImage.gameObject.GetComponent<RectTransform>().sizeDelta.x;
buttonsPosCache = buttons.anchoredPosition;
}
//Update
private void Update()
{
if (video.isPlaying)
{
if (!video.isPrepared) return;
videoSlider.value = (float)NTime;
video.SetDirectAudioVolume(0, volumeSlider.value);
}
if (fullScreen)
{
if (Input.GetAxis("Mouse X") != 0 || Input.GetAxis("Mouse Y") != 0)
{
timerMouse = 0;
buttons.gameObject.SetActive(true);
}
else
{
timerMouse += Time.deltaTime;
if (timerMouse > 3)
{
timerMouse = 3;
buttons.gameObject.SetActive(false);
}
}
}
}
public ulong Duration
{
get { return (ulong)(video.frameCount / video.frameRate); }
}
public double VideoTime
{
get { return video.time; }
}
public double NTime
{
get { return VideoTime / Duration; }
}
//Prepare Method
public void LoadVideo(string source)
{
video.url = System.IO.Path.Combine(Application.streamingAssetsPath, source);
video.Prepare();
}
//Methods for Buttons
public void PlayVideo()
{
//if (!IsPrepared && IsPlaying) return ;
video.Play();
}
public void PauseVideo()
{
if (!video.isPlaying) return;
video.Pause();
}
public void SeekSlider()
{
video.time = (videoSlider.value * Duration);
}
public void PauseResume()
{
//if (!IsPrepared) return ;
videoRectangle.SetActive(true);
if (video.isPlaying)
{
playButton.image.sprite = Resources.LoadAll<Sprite>("icons")[25];
PauseVideo();
}
else if (!video.isPlaying)
{
playButton.image.sprite = Resources.LoadAll<Sprite>("icons")[24];
PlayVideo();
}
}
public void FullScreen()
{
if (!fullScreen)
{
disableButton.SetActive(false);
fullScreenImage.gameObject.GetComponent<RectTransform>().sizeDelta = new Vector2(1920, 1920);
buttons.anchoredPosition = buttonsPos;
fullScreen = true;
}
else
{
disableButton.SetActive(true);
fullScreenImage.gameObject.GetComponent<RectTransform>().sizeDelta = new Vector2(videoWidth, videoHeight);
buttons.anchoredPosition = buttonsPosCache;
fullScreen = false;
}
}
public void ChangeVideoLanguage()
{
if (!languageChange)
{
buttonLanguage.text = "EN";
videoFileName = videoFileNameDE;
video.Stop();
playButton.image.sprite = Resources.LoadAll<Sprite>("icons")[25];
LoadVideo(videoFileName);
languageChange = true;
}
else
{
buttonLanguage.text = "DE";
videoFileName = videoFileNameEN;
video.Stop();
playButton.image.sprite = Resources.LoadAll<Sprite>("icons")[25];
LoadVideo(videoFileName);
languageChange = false;
}
}
}

I can't jump and move at the same time unity2d

i made 2d character and 3 ui buttons and they worked well
but the problem is when moving to the right or left by the ui buttons i can't jump however when jump from the ui button i can move to right and left
this is the script
public class PlayerWalk : MonoBehaviour {
private PlayerAnimation playerAnim;
private Rigidbody2D myBody;
private SpriteRenderer spriteRenderer;
public float speed = 7f;
public float jumpForce = 7f;
private bool moveLeft; // determine if we move left or right
private bool dontMove; // determine if we are moving or not
private bool canJump; // we will test if we can jump
void Start () {
playerAnim = GetComponent<PlayerAnimation>();
myBody = GetComponent<Rigidbody2D>();
dontMove = true;
}
void Update () {
//DetectInput();
HandleMoving();
}
void HandleMoving() {
if (dontMove) {
StopMoving();
} else {
if (moveLeft) {
MoveLeft();
} else if (!moveLeft) {
MoveRight();
}
}
} // handle moving
public void AllowMovement(bool movement) {
dontMove = false;
moveLeft = movement;
}
public void DontAllowMovement() {
dontMove = true;
}
public void Jump() {
if(canJump) {
myBody.velocity = new Vector2(myBody.velocity.x, jumpForce);
//myBody.AddForce(Vector2.right * jumpForce);
}
}
// PREVIOUS FUNCTIONS
public void MoveLeft() {
myBody.velocity = new Vector2(-speed, myBody.velocity.y);
playerAnim.ZombieWalk(true, true);
}
public void MoveRight() {
myBody.velocity = new Vector2(speed, myBody.velocity.y);
playerAnim.ZombieWalk(true, false);
}
public void StopMoving() {
playerAnim.ZombieStop();
myBody.velocity = new Vector2(0f, myBody.velocity.y);
}
void DetectInput() {
float x = Input.GetAxisRaw("Horizontal");
if (x > 0)
{
MoveRight();
}
else if (x < 0)
{
MoveLeft();
}
else
{
StopMoving();
}
}
void OnCollisionEnter2D(Collision2D collision) {
if(collision.gameObject.tag == "Ground") {
canJump = true;
}
}
void OnCollisionExit2D(Collision2D collision) {
if (collision.gameObject.tag == "Ground") {
canJump = false;
}
}
} // class
the 2d character moves well and there is no bugs or problems with scripts
Any help??
I don't know where is the problem??
**Note ** i used unity5.6
I would say onTriggerEnter2D instead of using onCollisionEnter2D would be a better option in this scenario. You can read more about that here.
https://answers.unity.com/questions/875770/ontriggerenter-or-oncollisionenter-1.html#:~:text=OnCollisionEnter%20is%20called%20when%20two,with%20%22IsTrigger%22%20set).
Did you try to debug the value of canJump while you are trying to move left or right?

Compiler generates "error CS1513: } expected", but } is there

I am following a tutorial where I build my first 2D game in Unity.
I added a flipX function to flip my Sprite when I change my direction (pressing A or D)
I tried to use the same script, and tried to compile it there are 2 errors:
Assets\Scripts\Player.cs(83,25): error CS1002: ; expected
Assets\Scripts\Player.cs(83,25): error CS1513: } expected
I know what they mean and checked my script. I'm sure they are there where they are not. I just can't figure out the error.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
private Rigidbody2D _rigid;
[SerializeField]
private float _jumpForce = 5.0f;
private bool _resetJump = false;
[SerializeField]
private float _speed = 3.5f;
private PlayerAnimation _playerAnim;
private SpriteRenderer _playerSprite;
// Start is called before the first frame update
void Start()
{
_rigid = GetComponent<Rigidbody2D>();
_playerAnim = GetComponent<PlayerAnimation>();
_playerSprite = GetComponentInChildren<SpriteRenderer>();
}
// Update is called once per frame
void Update()
{
Movement();
}
void Movement()
{
float horizontalInput = Input.GetAxisRaw("Horizontal");
if (horizontalInput > 0)
{
Flip(true);
}
else if (horizontalInput < 0)
{
Flip(false);
}
if (Input.GetKeyDown(KeyCode.Space) && IsGrounded() == true)
{
Debug.Log("Jump!");
_rigid.velocity = new Vector2(_rigid.velocity.x, _jumpForce);
StartCoroutine(ResetJumpRoutine());
}
_rigid.velocity = new Vector2(horizontalInput * _speed, _rigid.velocity.y);
_playerAnim.Move(horizontalInput);
}
bool IsGrounded()
{
RaycastHit2D hitInfo = Physics2D.Raycast(transform.position, Vector2.down, 0.6f, 1 << 8);
if (hitInfo.collider != null)
{
if (_resetJump == false)
return true;
}
return false;
}
void Flip(bool faceRight)
{
if (faceRight == true)
{
_playerSprite.flipX = false;
}
else if (faceRight == false)
{
_playerSprite,flipX = true;
}
}
IEnumerator ResetJumpRoutine()
{
_resetJump = true;
yield return new WaitForSeconds(0.1f);
_resetJump = false;
}
}
It's a simple mistake, replace _playerSprite,flipX = true; with _playerSprite.flipX = true;.
You have a comma instead of a dot.

When the player shoots it is losing life

I'm making a multiplayer game2d and when my player shoots (the gun has a collider too )it's affecting his life and I don't know why.Probably because when the target "hurt" has RPCtarget.all but I don't know with what to change just to affect the others players in the game , not mine. With what I can replace all?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using Photon.Pun;
using Photon.Realtime;
using Photon;
using UnityEngine.UI;
public class Character : MonoBehaviourPun,IPunObservable
{
Rigidbody2D rb;
float dirX;
[SerializeField]
float moveSpeed = 5f, jumpForce = 400f, bulletSpeed = 500f;
[SerializeField] private float health = 100;
[SerializeField] private Slider slider;
[SerializeField] private Gradient gradient;
[SerializeField] private Image fill;
public Rigidbody2D bulletPrefabs;
Vector3 localScale;
public DeathsCount myCounts;
public Transform barrel;
public Rigidbody2D bullet;
// Use this for initialization
void Start()
{
localScale = transform.localScale;
rb = GetComponent<Rigidbody2D>();
if (photonView.IsMine)
{
myCounts = FindObjectOfType<DeathsCount>();
}
else
{
}
}
public float Health
{
get { return health; }
set
{
health = value;
slider.value = health;
// fill.color = gradient.Evaluate(slider.normalizedValue);
}
}
private void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.CompareTag("Hurt"))
{
if (photonView.IsMine)
{
photonView.RPC("Damage", RpcTarget.All);
}
}
if (col.gameObject.tag == "PowerUp")
{
if (photonView.IsMine)
{
var powerup = col.GetComponent<PowerUp>();
powerup.Pickup(this);
}
else
{
}
}
if (col.gameObject.CompareTag("Bullet"))
{
if (photonView.IsMine)
{
photonView.RPC("Damage", RpcTarget.All);
bullet = bulletPrefabs;
}
}
else
{
}
}
[PunRPC]
void Damage()
{
if (Health > 0)
{
Health -= 20;
}
if (Health <= 0) // check health status
{
Health = 0; // make that Heath don't be < 0
if (photonView.IsMine)
{
myCounts.RpcRespawn(); //Here you should to call counter
photonView.transform.position = Vector2.zero;
Health = 100;
}
}
}
// Update is called once per frame
void Update()
{
if (photonView.IsMine)
{
dirX = CrossPlatformInputManager.GetAxis("Horizontal");
if (dirX != 0)
{
barrel.up = Vector3.right * Mathf.Sign(dirX);
}
if (CrossPlatformInputManager.GetButtonDown("Jump"))
Jump();
if (CrossPlatformInputManager.GetButtonDown("Fire1"))
Fire();
}
else
{
}
}
void FixedUpdate()
{
if (photonView.IsMine)
{
rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);
}
}
void Jump()
{
if (photonView.IsMine)
{
if (rb.velocity.y == 0)
rb.AddForce(Vector2.up * jumpForce);
}
}
void Fire()
{
var firedBullet = PhotonNetwork.Instantiate(bullet.name, barrel.position, barrel.rotation).GetComponent<Rigidbody2D>();
firedBullet.AddForce(barrel.up * bulletSpeed);
}
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (stream.IsWriting)
{
stream.SendNext(Health);
}
else if (stream.IsReading)
{
Health = (float)stream.ReceiveNext();
}
}
public void SetMaxHealth(int value)
{
if (photonView.IsMine)
{
slider.maxValue = value;
// The property handles the rest anyway
Health = value;
}
}
}
I think you don't really need RPC in this case.
I see your character IPunObservable and, I guess, added to PhotonView. So its health will sync automatically.
You also instantiate bullets with PhotonNetwork, which means, they will sync too and have PhotonView.
So every player has all synchronized bullets and other players.
It means, all that you need is to check if bullet is from other player and set damage locally (don't worry, result will sync) like this :
. . .
private void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.CompareTag("Hurt"))
{
// if hurt object is not mine, take damage
if (!col.gameObject.GetPhotonView().isMine)
Damage();
}
if (col.gameObject.tag == "PowerUp")
{
if (photonView.IsMine)
{
var powerup = col.GetComponent<PowerUp>();
powerup.Pickup(this);
}
else
{
}
}
if (col.gameObject.CompareTag("Bullet"))
{
// if bullet is not mine, take damage
if (!col.gameObject.GetPhotonView().isMine)
Damage();
}
else
{
}
}
// no rpc
void Damage()
{
if (!photonView.IsMine) // only player can change his life
return;
if (Health > 0)
{
Health -= 20;
}
if (Health <= 0) // check health status
{
myCounts.RpcRespawn(); //Here you should to call counter
photonView.transform.position = Vector2.zero;
Health = 100;
}
}

Unity 2D draggable movement control

I want to add a draggable-movement control thing (attached image) like Fifa mobile game in my 2D app.
I searched a lot for the idea or a basic tutorial or relevant Unity asset. But didn't find one.
Help me with an example or URL.
You can use this if you would like, it works on web and mobile
using UnityEngine;
using System.Collections;
public class JoyStick : MonoBehaviour {
public Texture areaTexture;
public Texture touchTexture;
public Vector2 joystickPosition = new Vector2( 50f,50f);
public Vector2 speed = new Vector2(2,100);
public float zoneRadius=100f;
public float touchSize = 30;
public float deadZone=20;
public float touchSizeCoef=0;
protected Vector2 joystickAxis;
protected Vector2 joystickValue;
public Vector2 joyTouch;
private Vector2 _joystickCenter;
[SerializeField]
private Vector2 _smoothing = new Vector2(20f,20f);
public Vector2 Smoothing
{
get {
return this._smoothing;
}
set {
_smoothing = value;
if (_smoothing.x<0.1f){
_smoothing.x=0.1f;
}
if (_smoothing.y<0.1){
_smoothing.y=0.1f;
}
}
}
private int _joystickIndex=-1;
private bool _enaReset;
private bool _enaZoom;
void Start ()
{
zoneRadius = Screen.width*0.07f;
touchSize = Screen.width*0.07f;
joystickPosition = new Vector2(Screen.width*0.12f,Screen.width*0.12f);
_joystickCenter = joystickPosition;
_enaReset=false;
}
void Update ()
{
if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.Android)
{
foreach (Touch touch in Input.touches)
{
if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
{
if (_joystickIndex==touch.fingerId){
_joystickIndex=-1;
_enaReset=true;
}
}
if(_joystickIndex==touch.fingerId)
{
OnTouchDown(touch.position);
}
if (touch.phase == TouchPhase.Began)
{
if (((Vector2)touch.position - _joystickCenter).sqrMagnitude < Mathf.Pow((zoneRadius+touchSizeCoef/2),2))
{
_joystickIndex = touch.fingerId;
}
}
}
UpdateJoystick();
if(_enaReset)
{
ResetJoystick();
}
}
else
{
if (Input.GetButtonUp ("Fire1"))
{
_joystickIndex=-1;
_enaReset=true;
}
if(_joystickIndex==1)
{
OnTouchDown(Input.mousePosition);
}
if (Input.GetButtonDown ("Fire1") )
{
if (((Vector2)Input.mousePosition - _joystickCenter).sqrMagnitude <Mathf.Pow( (zoneRadius+touchSizeCoef/2),2))
{
_joystickIndex = 1;
}
}
if(_enaReset)
{
ResetJoystick();
}
UpdateJoystick();
}
}
private void UpdateJoystick()
{
if (joyTouch.sqrMagnitude>deadZone*deadZone)
{
joystickAxis = Vector2.zero;
if (Mathf.Abs(joyTouch.x)> deadZone)
{
joystickAxis = new Vector2( (joyTouch.x -(deadZone*Mathf.Sign(joyTouch.x)))/(zoneRadius-touchSizeCoef-deadZone),joystickAxis.y);
}
else
{
joystickAxis = new Vector2( joyTouch.x /(zoneRadius-touchSizeCoef),joystickAxis.y);
}
if (Mathf.Abs(joyTouch.y)> deadZone)
{
joystickAxis = new Vector2( joystickAxis.x,(joyTouch.y-(deadZone*Mathf.Sign(joyTouch.y)))/(zoneRadius-touchSizeCoef-deadZone));
}
else{
joystickAxis = new Vector2( joystickAxis.x,joyTouch.y/(zoneRadius-touchSizeCoef));
}
}
else{
joystickAxis = new Vector2(0,0);
}
Vector2 realvalue = new Vector2( speed.x*joystickAxis.x,speed.y*joystickAxis.y);
joystickValue=realvalue;
//print(realvalue);
}
void OnTouchDown(Vector2 position)
{
joyTouch = new Vector2( position.x, position.y) - _joystickCenter;
if ((joyTouch/(zoneRadius-touchSizeCoef)).sqrMagnitude > 1)
{
joyTouch.Normalize();
joyTouch *= zoneRadius-touchSizeCoef;
}
//print(joyTouch);
}
private void ResetJoystick()
{
if (joyTouch.sqrMagnitude>0.1)
{
joyTouch = new Vector2( joyTouch.x - joyTouch.x*_smoothing.x*Time.deltaTime, joyTouch.y - joyTouch.y*_smoothing.y*Time.deltaTime);
}
else{
joyTouch = Vector2.zero;
_enaReset=false;
}
}
void OnGUI()
{
GUI.DrawTexture( new Rect(_joystickCenter.x -zoneRadius ,Screen.height- _joystickCenter.y-zoneRadius,zoneRadius*2,zoneRadius*2), areaTexture,ScaleMode.ScaleToFit,true);
GUI.DrawTexture( new Rect(_joystickCenter.x+(joyTouch.x -touchSize) ,Screen.height-_joystickCenter.y-(joyTouch.y+touchSize),touchSize*2,touchSize*2), touchTexture,ScaleMode.ScaleToFit,true);
}
}