Unity-How to stop a moving object when the Camera sees it - unity3d

This is just a simple thing I want to do. I have my cube gameobject rotating and I want to make it so when the camera sees the cube, it stops rotating. If you could steer me in the right direction, I'd appreciate it. thank you
public class cubeMove : MonoBehaviour, MoveObject
{
public Renderer rend;
public void Update () {
rend = GetComponent<Renderer>();
stopWhenSeen();
}
public void move()
{
transform.Rotate(new Vector3(15, 30, 45) * Time.deltaTime);
}
public void stopWhenSeen()
{
if (rend.enabled == false)
{
move();
}
}
}

Implement the OnBecameVisible and OnBecameInvisible MonoBehaviour's message :
private visible = false ;
// OnBecameVisible is called when the renderer became visible by any camera. INCLUDING YOUR EDITOR CAMERA
void OnBecameVisible()
{
visible = true ;
}
// OnBecameInvisible is called when the renderer is no longer visible by any camera. INCLUDING YOUR EDITOR CAMERA
void OnBecameInvisible()
{
visible = false;
}
void Update()
{
if( !visible )
move() ;
}
public void move()
{
transform.Rotate(new Vector3(15, 30, 45) * Time.deltaTime);
}

https://docs.unity3d.com/ScriptReference/Renderer-isVisible.html
You could try the .isVisible bool in your update method.
Here is a thread with other suggestions:
http://answers.unity3d.com/questions/8003/how-can-i-know-if-a-gameobject-is-seen-by-a-partic.html

Related

Access to childs of my main GameObject. Unity

I have some childs on my main gameobject, what am I down wrong on the below code? I bassically want to access to the sprite renderer of the childs of my game object,
If I put that code on the direct child that have the sprite render I can access to the sprite with GetComponent, please if anyone know what can I do let me know
SpriteRenderer sprite;
private bool changeColorState = false;
public float time;
void Start(){
sprite = GetComponentsInChildren<SpriteRenderer>();
}
void Update(){
StartCoroutine(timeOfColorChange());
}
IEnumerator timeOfColorChange(){
yield return new WaitForSeconds(time);
if (changeColorState) {
chooseColor(.5f);
} else {
chooseColor(1f);
}
}
private void OnTriggerEnter2D(Collider2D otherObject){
if (otherObject.GetComponent<Player>()) {
changeColorState = true;
}
}
private void OnTriggerExit2D(Collider2D otherObject){
if (otherObject.GetComponent<Player>()) {
changeColorState = false;
}
}
public void chooseColor(float float1){
this.GetComponent<SpriteRenderer>().color = new Color(1f, 1f, 1f, float1);
}
I've tried GetComponentsOnChild but it's not working
You're not using the "sprite" variable inside chooseColor, where you're using GetComponent instead of GetComponentInChildren. Swap it for sprite.color and it should work.

explosion animation not in the right place when it is played

I was making an enemy death animation on unity(again) when it did not want to work, now when I say it did not want to work I mean it did not want to work in the position it is supposed to be in(which is where the enemy is)
public class EnemyController : MonoBehaviour
{
public int health = 3;
public GameObject explosion;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void TakeDamage()
{
health--;
if(health <= 0)
{
Destroy(gameObject);
Instantiate(explosion, transform.position, transform.rotation);
}
}
}
You're using the transform of an object that you have already destroyed, as transform is a property of gameObject.
Try instantiating the Explosion prefab before calling Destroy(gameobject).
public void TakeDamage()
{
health--;
if (health <= 0)
{
Instantiate(explosion, transform.position, transform.rotation);
Destroy(gameObject);
}
}

Unity Rotate object with PS4 controller

I'm new to Unity but I'm trying to rotate an object around the Y axis using controller input (right stick). So if the stick is pushed right, the object will rotate towards the right. Here is my code so far.
public class TurnBall : MonoBehaviour {
PlayerControls controls;
Vector2 aim;
void Awake() {
controls = new PlayerControls();
controls.Gameplay.Aim.performed += ctx => aim = ctx.ReadValue<Vector2>();
controls.Gameplay.Aim.canceled += ctx => aim = Vector2.zero;
}
void Update() {
transform.Rotate(0, aim.x, 0, Space.World);
}
void onEnable() {
controls.Gameplay.Enable();
}
void onDisable() {
controls.Gameplay.Disable();
}
}
Thanks in advance!!

Jittery movement of the camera when rotating AND moving - 2D top down Unity

I am making a 2d top down game where the player can rotate the camera around himself as he moves through the world.
Everything works fine when the player is moving around the world the camera follows him fine. if he standing still then the camera rotation also works very well. However as soon as I start to do both then there is a jittery in the camera that makes all other objects jitter besides the player.
Now in working with this problem I have found out that this could have to do with the fact that I use rigidbody2d.AddRelativeForce (so physics) to move the player and that his movements are checked in FixedUpdate.
https://forum.unity3d.com/threads/camera-jitter-problem.115224/ http://answers.unity3d.com/questions/381317/camera-rotation-jitterness-lookat.html
I have tried moving my camera rotation and the following scripts to LateUpdate, FixedUpdate, Update you name it. Nothing seems to work. I am sure that there is some sort of delay between movement of the camera and the rotation that is causing this. I am wondering if anyone has any feedback?
I have tried disabling Vsync, does not remove it entirely
I have tried interpolating and extrapolating the rigidbody and although there is a difference it does not remove it entirely. Ironically it seemd if I have it set to none, it works best.
Scripts:
To Follow character, script applied to a gameobject that has the camera as a child
public class FollowPlayer : MonoBehaviour {
public Transform lookAt;
public Spawner spawner;
private Transform trans;
public float cameraRot = 3;
private bool smooth = false;
private float smoothSpeed = 30f;
private Vector3 offset = new Vector3(0, 0, -6.5f);
//test
public bool changeUpdate;
private void Start()
{
trans = GetComponent<Transform>();
}
private void FixedUpdate()
{
CameraRotation();
}
private void LateUpdate()
{
following();
}
public void following()
{
Vector3 desiredPosition = lookAt.transform.position + offset;
if (smooth)
{
transform.position = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
}
else
{
transform.position = desiredPosition;
}
}
void CameraRotation()
{
if (Input.GetKey("q"))
{
transform.Rotate(0, 0, cameraRot);
}
if (Input.GetKey("e"))
{
transform.Rotate(0, 0, -cameraRot);
}
}
public void SetTarget(string e)
{
lookAt = GameObject.Find(e).GetComponent<Transform>();
}
}
The character Controller, script applied to the Player, is called in FixedUpdate
private void HandleMovement()
{
if (Input.GetKey("w"))
{
rigid.AddRelativeForce(Vector2.up * speed);
}
if (Input.GetKey("s"))
{
rigid.AddRelativeForce(Vector2.down * speed);
}
if (Input.GetKey("a"))
{
if (facingRight)
{
Flip();
}
rigid.AddRelativeForce(Vector2.left * speed);
}
if (Input.GetKey("d"))
{
if (!facingRight)
{
Flip();
}
rigid.AddRelativeForce(new Vector2(1,0) * speed);
}
}
Try to use Coroutines. I modified some of my scripts to be more familiar to Your code, tried it, and I didn't see any jittery. I hope that will help You.
Camera Class:
public class CameraController : MonoBehaviour {
[SerializeField]
Transform CameraRotator, Player;
[SerializeField]
float rotationSpeed = 10f;
float rotation;
bool rotating = true;
void Start()
{
StartCoroutine(RotatingCamera());
}
IEnumerator RotatingCamera()
{
while (rotating)
{
rotation = Input.GetAxis("HorizontalRotation");
CameraRotator.Rotate(Vector3.up * Time.deltaTime * rotation * rotationSpeed);
CameraRotator.position = Player.position;
yield return new WaitForFixedUpdate();
}
}
private void OnDestroy()
{
StopAllCoroutines();
}
}
Player Class:
public class PlayerMovement : MonoBehaviour {
[SerializeField]
float movementSpeed = 500f;
Vector3 movementVector;
Vector3 forward;
Vector3 right;
[SerializeField]
Transform CameraRotator;
Rigidbody playerRigidbody;
float inputHorizontal, inputVertical;
void Awake()
{
playerRigidbody = GetComponent<Rigidbody>();
StartCoroutine(Moving());
}
IEnumerator Moving()
{
while (true)
{
inputHorizontal = Input.GetAxis("Horizontal");
inputVertical = Input.GetAxis("Vertical");
forward = CameraRotator.TransformDirection(Vector3.forward);
forward.y = 0;
forward = forward.normalized;
Vector3 right = new Vector3(forward.z, 0, -forward.x);
movementVector = inputHorizontal * right + inputVertical * forward;
movementVector = movementVector.normalized * movementSpeed * Time.deltaTime;
playerRigidbody.AddForce(movementVector);
yield return new WaitForFixedUpdate();
}
}
}
I fixed this problem finally:
First I made my cameraRotation() and follow() into 1 function and gave it a better clearer name:
public void UpdateCameraPosition()
{
if (Input.GetKey("q"))
{
transform.Rotate(0, 0, cameraRot);
}
else if (Input.GetKey("e"))
{
transform.Rotate(0, 0, -cameraRot);
}
Vector3 desiredPosition = lookAt.transform.position + offset;
transform.position = desiredPosition;
}
I then called that function from the character controller straight after the handling of movement. Both calls (handleMovement & cameraPosition) in fixedUpdate.
void FixedUpdate()
{
HandleMovement();
cameraController.UpdateCameraPosition();
}
and the jittering was gone.
So it seems it was imply because there was a slight delay between the two calls as the previous posts I read had said. But I had failed to be able to properly Set them close enough together.
Hope this helps someone.

How to simulate a mouse up event?

There is a bug in my code: When I release the mouse out of the screen, the unity can't detect "GetMouseButtonUp", and when I move the released mouse back to the screen, it detects the "GetMouseButton" which should not.
So when the mouse out of the screen, I want simulate send a mouse up event to let the unity detect "GetMouseButtonUp".
How to simulate a mouse event?
Pseudo code
bool mouseIsDown = false;
public void Update()
{
Rect screenRect = new Rect(-Screen.width/2, -Screen.height/2, Screen.width, Screen.height);
If(screenRect.Contains(Input.mousePosition))
{
if(mouseIsDown && !Input.GetMouseButton(0))
OnMouseUp();
if(Input.GetMouseButton(0))
{
OnMouse();
if(!mouseIsDown)
{
OnMouseDown();
mouseIsDown = true;
}
}
}
}
public void OnMouseDown()
{
// Do something
}
public void OnMouse()
{
// Do something
}
public void OnMouseUp()
{
// Do something
}
I am not sure if I correctly understand your question. But, you can use these functions the same way you would use the Start() Update() Awake() etc. functions
void OnMouseUp () {
}
void OnMouseDown (){
}