Why the OnMouseDown() event on Rigidbody does not fire? - unity3d

There is a dynamic Rigidbody that can be launched with the mouse. But at some point, Rigidbody stops reacting to the mouse for some reason. Rigidbody's speed is 0.
To a rigidbody attached two Spring joints.
The only way to awaken the body is to disable and re-enable Spring Joints when debugging.
public class Ball : MonoBehaviour
{
private Rigidbody2D rigidbodyBall;
public SpringJoint2D[] springJoints;
private GameObject speed;
public static Ball instance = null;
#region Life Cycle
void Awake()
{
speed = GameObject.Find("Velocity");
springJoints = GetComponents<SpringJoint2D>();
rigidbodyBall = GetComponent<Rigidbody2D>();
gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
}
private bool clickedOn = false;
void Update()
{
if (clickedOn)
{
Dragging();
UIManager.instance.pauseButton.SetActive(false);
UIManager.instance.totalScoreUI.gameObject.SetActive(false);
}
else
{
UIManager.instance.pauseButton.SetActive(true);
UIManager.instance.totalScoreUI.gameObject.SetActive(true);
}
}
#endregion
#region Launcher
#region Mouse
void OnMouseDown()
{
SpringJointDeactivate();
clickedOn = true;
}
void OnMouseUp()
{
SpringJointActivate();
clickedOn = false;
SetKinematicState(false);
Invoke("SpringJointDeactivate", 0.1f);
}
void Dragging()
{
Vector3 mouseWorldPointStart = transform.position;
Vector3 mouseWorldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mouseWorldPoint.z = 0f;
if (Boundary.ballInBoundary)
{
transform.position = mouseWorldPoint;
float diffX = mouseWorldPoint.x - mouseWorldPointStart.x;
//TODO
for (int i = 0; i < springJoints.Length; i++)
{
springJoints[i].connectedAnchor = new Vector2(springJoints[i].connectedAnchor.x + diffX, springJoints[i].connectedAnchor.y);
}
}
else
{
Debug.Log("Another situation!");
Debug.Log(Boundary.ballInBoundary);
}
}
#endregion
public void SpringJointActivate()
{
foreach (SpringJoint2D joint in springJoints)
{
joint.enabled = true;
}
}
public void SpringJointDeactivate()
{
foreach (SpringJoint2D joint in springJoints)
{
joint.enabled = false;
}
}
public Vector3[] GetSpringJointsConnectedAnchorCoord()
{
Vector3[] springJointsCoord = new[] { Vector3.zero, Vector3.zero };
for (int i = 0; i < springJoints.Length; i++)
{
springJointsCoord[i] = springJoints[i].connectedAnchor;
}
return springJointsCoord;
}
#endregion
public void SetKinematicState(bool kinematicState)
{
rigidbodyBall.isKinematic = kinematicState;
}
}
What is the reason for this? How can this be corrected?

Replaced OnMouseDown() with Input.GetMouseButtonDown(0) and everything worked out.
void Update()
{
if (Input.GetMouseButtonDown(0))
{
SpringJointDeactivate();
clickedOn = true;
}
if (Input.GetMouseButtonUp(0))
{
SpringJointActivate();
clickedOn = false;
SetKinematicState(false);
Invoke("SpringJointDeactivate", 0.1f);
}
}

Related

How do I make my player idle or add speed for when im moving up or down in Unity(2021)?

Here's my code for player movement. I have set up walking around and I am now Trying to change the sprite animation when walking in different directions. Everything was working fine but when I tried to change the sprite for walking up the sprite gets stuck in a loop and doesn't idle.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Animator Animator;
[SerializeField] private float speed = 1f;
private Rigidbody2D body;
private Vector2 axisMovement;
// Start is called before the first frame update
void Start()
{
body = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
axisMovement.x = Input.GetAxisRaw("Horizontal");
axisMovement.y = Input.GetAxisRaw("Vertical");
Animator.SetFloat("Speed", Mathf.Abs(axisMovement.x));
if (Input.GetKey(KeyCode.W))
{
Animator.SetBool("isforward", true);
}
if (Input.GetKey(KeyCode.A))
{
Animator.SetBool("isforward", false);
}
if (Input.GetKey(KeyCode.S))
{
Animator.SetBool("isforward", false);
}
if (Input.GetKey(KeyCode.D))
{
Animator.SetBool("isforward", false);
}
}
private void FixedUpdate()
{
Move();
}
private void Move()
{
body.velocity = axisMovement.normalized * speed;
CheckForFlipping();
}
private void CheckForFlipping()
{
bool movingLeft = axisMovement.x < 0;
bool movingRight = axisMovement.x > 0;
if (movingLeft)
{
transform.localScale = new Vector3(-1f, transform.localScale.y);
}
if (movingRight)
{
transform.localScale = new Vector3(1f, transform.localScale.y);
}
}
}
I also tried doing Animator.SetFloat("Speed", Mathf.Abs(axisMovement.x)); but switch it with axisMovement.y but that stops all the animations moving left and right stop working. 😢
I've figured it out. here's the updated code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Animator Animator;
[SerializeField] private float speed = 1f;
private Rigidbody2D body;
private Vector2 axisMovement;
// Start is called before the first frame update
void Start()
{
body = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
axisMovement.x = Input.GetAxisRaw("Horizontal");
axisMovement.y = Input.GetAxisRaw("Vertical");
Animator.SetFloat("Speed", Mathf.Abs(axisMovement.x + axisMovement.y));
if (Input.GetKey(KeyCode.W))
{
Animator.SetBool("isforward", true);
} else {
Animator.SetBool("isforward", false);
}
// if (Input.GetKey(KeyCode.A))
// {
// Animator.SetBool("isforward", false);
// }
// if (Input.GetKey(KeyCode.S))
// {
// Animator.SetBool("isforward", false);
// }
// if (Input.GetKey(KeyCode.D))
// {
// Animator.SetBool("isforward", false);
// }
}
private void FixedUpdate()
{
Move();
}
private void Move()
{
body.velocity = axisMovement.normalized * speed;
CheckForFlipping();
}
private void CheckForFlipping()
{
bool movingLeft = axisMovement.x < 0;
bool movingRight = axisMovement.x > 0;
if (movingLeft)
{
transform.localScale = new Vector3(-1f, transform.localScale.y);
}
if (movingRight)
{
transform.localScale = new Vector3(1f, transform.localScale.y);
}
}
}

after adding animation to the player's code in the play mode, he stopped moving

When creating the game, I came across the problem that after adding animation to the player's code in the play mode, he stopped moving.
I did everything as usual, went into the animator, made an animation, and then set up and added everything necessary to the code in the animator, but after that the player stopped moving although before that everything was fine.
Help me, I hope it's not difficult.
Here is the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[Header("Controlled player")]
public Rigidbody2D rb;
[Header("Tinctures of movement")]
public float PSpeed = 1f;
public float jumpForce = 1f;
[Header("Variable Reduction parameters")]
public float LowingPSPeed;
public float FormedPSpeed;
[Header("Traffic Statuses")]
public bool Move;
public bool Jump;
[Header("")]
[Header("Checking the ground under the player")]
public bool OnGround;
private bool doJump = false;
private bool GOright = false;
private bool GOleft = false;
[Header("Ground Check Settings")]
private float groundRadius = 0.3f;
public Transform groundCheck;
public LayerMask groundMask;
private Animator anim;
void Math()
{
FormedPSpeed = PSpeed / LowingPSPeed;
}
void Start()
{
anim = GetComponent<Animator>();
}
void Update()
{
Math();
if (Input.GetKeyDown(KeyCode.Space))
{
doJump = true;
}
if (Input.GetKey("d"))
{
GOright = true;
}else
{
GOright = false;
}
if (Input.GetKey("a"))
{
GOleft = true;
}
else
{
GOleft = false;
}
}
void FixedUpdate()
{
OnGround = Physics2D.OverlapCircle(groundCheck.position, groundRadius, groundMask);
if (GOright && Move)
{
transform.position += new Vector3(FormedPSpeed, 0, 0);
GetComponent<SpriteRenderer>().flipX = false;
}
if (GOleft && Move)
{
transform.position += new Vector3(-(FormedPSpeed), 0, 0);
GetComponent<SpriteRenderer>().flipX = true;
}
if (doJump && Jump && OnGround)
{
rb.AddForce(new Vector2(0, (jumpForce * 10)));
anim.SetTrigger("takeOf");
doJump = false;
}
if (OnGround)
{
anim.SetBool("isJump", false);
}else
{
anim.SetBool("isJump", true);
}
if (!GOleft && !GOright)
{
anim.SetBool("isRun", false);
}else
{
anim.SetBool("isRun", true);
}
}
I don't understand why this is happening

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?

Can't figure out how to stop zombie from dealing damage when no longer colliding with player

I am creating a top down zombie shooter and I have made the zombie do damage to the player when it is touching the player. However when the player backs away from the zombie after taking damage, the players health will continue to drop. Any ideas on how to fix this would be appreciated.
public float moveSpeed= 5f;
public Rigidbody2D rb;
public Camera cam;
public float playerHealth = 100;
public float enemyDamage = 25;
public GameObject gameOverScreen;
Vector2 movement;
Vector2 mousePos;
// Update is called once per frame
void Update()
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
if(playerHealth == 0)
{
gameOverScreen.SetActive(true);
}
}
void FixedUpdate()
{
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
Vector2 lookDir = mousePos - rb.position;
float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
rb.rotation = angle;
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
StartCoroutine(DamagePlayer());
}
else
{
StopCoroutine(DamagePlayer());
}
}
IEnumerator DamagePlayer()
{
while(true)
{
yield return new WaitForSeconds(1);
playerHealth -= enemyDamage;
}
}
First of all for doing something if it is not colliding anymore you should use OnCollisionExit2D
Then you can either use it the way you did using
StopCoroutine(DamagePlayer());
Or if want to be sure you could either store a reference to your routine
private Coroutine routine;
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
if(routine == null)
{
routine = StartCoroutine(DamagePlayer());
}
}
else
{
if(routine != null) StopCoroutine(routine);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(routine != null) StopCoroutine (routine);
}
or use a bool flag in order to terminate it
private bool cancelRoutine = true;
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
if(cancelRoutine) routine = StartCoroutine(DamagePlayer());
}
else
{
cancelRoutine = true;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
cancelRoutine = true;
}
IEnumerator DamagePlayer()
{
cancelRoutine = false;
while(! cancelRoutine)
{
yield return new WaitForSeconds(1);
playerHealth -= enemyDamage;
}
}
In general you could solve this without a routine by directly using OnCollisionStay2D like e.g.
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
timer = 1;
}
}
void OnCollisionStay2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
timer -= Time.deltaTime;
if(timer <= 0)
{
timer = 1;
playerHealth -= enemyDamage;
}
}
}