Sprite not updating on collision - unity3d

Can someone explain why this code is not working as intended? Currently if there is a collision the sprite (flag) changes to green. The debug statements are working as I would expect but the sprite (flag) is not changed back to red in the event of no collision.
public Sprite gflag;
public Sprite rflag;
public SpriteRenderer render;
public GameObject Player;
private Checkpoint checkpoint;
private bool hit = false;
void Update()
{
if(hit != true)
{
Debug.Log("False!");
render.sprite = rflag;
}
}
// Modify color of flag depending on collision
void OnTriggerEnter2D(Collider2D collider)
{
if (collider.gameObject.tag == "Player")
{
Debug.Log("True!");
render.sprite = gflag;
hit = true;
}
}
Here is a screen shot of the checkpoint prefab:

Have you considered moving the logic in the Update() function to a OnTriggerExit2D function?
public Sprite gflag;
public Sprite rflag;
public SpriteRenderer render;
public GameObject Player;
private Checkpoint checkpoint;
private bool hit = false;
// Modify color of flag depending on collision
void OnTriggerEnter2D(Collider2D collider)
{
if (collider.gameObject.tag == "Player")
{
Debug.Log("True!");
render.sprite = gflag;
hit = true;
}
}
// Modify color of flag depending on collision
void OnTriggerExit2D(Collider2D collider)
{
if (collider.gameObject.tag == "Player")
{
Debug.Log("False!");
render.sprite = rflag;
hit = false;
}
}
This way, instead of checking in Update every frame, it will be handled within the collision functions entirely.
EDIT: To answer your initial question, the reason the code was not updating the flag back to red in the case of no collision is because you were not setting the hit boolean to false once the collision was exited.

Related

2D Player Shaking When Platforms Move Up and Down?

For some reason, my player character shakes up and down when the platform moves up and down, which prevents the player from jumping because the player is not grounded. I tried several things including adding a kinematic rigidbody to the platform and trying to make the player a child of the platform after landing on the platform but nothing has worked so far. Any help would be appreciated. Thank you!
Here is my code:
public class MovingPlatform : MonoBehaviour
{
private Vector3 posA;
private Vector3 posB;
private Vector3 nexPos;
public GameObject Player;
[SerializeField]
private float speed;
[SerializeField]
private Transform childTransform;
[SerializeField]
private Transform transformB;
void Start()
{
posB = childTransform.localPosition;
posB = transformB.localPosition;
nexPos = posB;
}
// Update is called once per frame
void Update()
{
Move();
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.tag == "Player")
{
collision.collider.transform.SetParent(transform);
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.collider.tag == "Player")
{
collision.collider.transform.SetParent(null);
}
}
private void Move()
{
childTransform.localPosition = Vector3.MoveTowards(childTransform.localPosition, nexPos, speed * Time.deltaTime);
if (Vector3.Distance(childTransform.localPosition,nexPos) <= 0.1)
{
ChangeDestination();
}
}
private void ChangeDestination()
{
nexPos = nexPos != posA ? posA : posB;
}
}
Move(); should be executed in lateupdate, because otherwise you will set the position of the player and later the physics system will update it, causing stuttering.
Another solution would be raycasting straight down and placing your GameObject on the collision point (plus some kind of offset)

How to spawn multiple prefab, with individual physics

I Did apply some of the responses , most likely in the wrong way.. this is still not working with this RAYCAST. What am I doing wrong here?
Want to spawn a prefab, which is a a ball, this ball is flying forward on flick finger on the screen.
What I want is to spawn OnClick FEW/Multiple of this prefab.
, prefab is spawning on Raycast Hit, BUT.. when I am flicking the object EVERY prefab in the scene is moving in the same way.
If I flick first one in to the Left, it goes there, but If now I flick second one to right, BOTH go to the RIGHT, but I would like them to work independent. Maybe this is easy fix to this but I can't find answer. (I'm planning to have up to 30/50 of this prefabs, so attaching separate scripts would be bit time consuming)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallScript1 : MonoBehaviour
{
Vector2 startPos, endPos, direction;
float touchTimeStart, touchTimeFinish;
public float timeInterval = 5f;
public float throwForceInXandY = 1f;
public float throwForceinZ = 40f;
public static bool SpawnButtonAppear = true;
public static bool thrown = false;
public static bool moving = false;
public static bool fly = false;
public bool Pressed = false;
Rigidbody rb;
public GameObject player;
public Vector3 originalPos;
public GameObject playerPrefab;
string touched;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.isKinematic = true;
}
private void OnMouseDown()
{
PlayerTest.clicked = true;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit _hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out _hit))
{
touched = _hit.collider.tag;
if (touched == "Player")
{
Invoke("spawned", 0.5f);
}
}
}
if (touched == "Player")
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
touchTimeStart = Time.time;
startPos = Input.GetTouch(0).position;
}
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
{
fly = false;
touchTimeFinish = Time.time;
endPos = Input.GetTouch(0).position;
direction = startPos - endPos;
rb.isKinematic = false;
rb.AddForce(-direction.x * throwForceInXandY, -direction.y * throwForceInXandY, throwForceinZ * timeInterval);
BackWall.canSpawnNow = 1;
}
}
}
public void spawned()
{
GameObject spawnedprefab = Instantiate(playerPrefab, new Vector3(originalPos.y, originalPos.x, originalPos.z), Quaternion.identity);
Destroy(spawnedprefab, 5f);
}
The thrown variable is not declared inside your class, so when you set it to true you are setting it true for all the instances of the class.
Declare the bool thrown; inside the EnemySpawn class, so that OnMouseDown, only the corresponding intance's thrown variable is set to true.

How to disable touch event in AR foundation (arkit)?

I'm not very good with Unity especially in AR, but I finally built my first AR game. However, there is one issue: when I place my game objects on the plane, I want them to be still and want them to move when I touch the display. Is there a way to disable the touch hit or whatever it is called?
......................................................................................................................................................................................................................................................................................................................................................................................................
enter code here
[RequireComponent(typeof(ARRaycastManager))]
public class PlaceOnPlane : MonoBehaviour
{
[SerializeField]
[Tooltip("Instantiates this prefab on a plane at the touch location.")]
GameObject m_PlacedPrefab;
/// <summary>
/// The prefab to instantiate on touch.
/// </summary>
public GameObject placedPrefab
{
get { return m_PlacedPrefab; }
set { m_PlacedPrefab = value; }
}
/// <summary>
/// The object instantiated as a result of a successful raycast
intersection with a plane.
/// </summary>
public GameObject spawnedObject { get; private set; }
void Awake()
{
m_RaycastManager = GetComponent<ARRaycastManager>();
}
bool TryGetTouchPosition(out Vector2 touchPosition)
{
#if UNITY_EDITOR
if (Input.GetMouseButton(0))
{
var mousePosition = Input.mousePosition;
touchPosition = new Vector2(mousePosition.x, mousePosition.y);
return true;
}
else
if (Input.touchCount > 0)
{
touchPosition = Input.GetTouch(0).position;
return true;
}
#endif
touchPosition = default;
return false;
}
void Update()
{
if (!TryGetTouchPosition(out Vector2 touchPosition))
return;
if (m_RaycastManager.Raycast(touchPosition, s_Hits, TrackableType.PlaneWithinPolygon))
{
// Raycast hits are sorted by distance, so the first one
// will be the closest hit.
var hitPose = s_Hits[0].pose;
if (spawnedObject == null)
{
spawnedObject = Instantiate(m_PlacedPrefab,
hitPose.position, hitPose.rotation);
}
else
{
spawnedObject.transform.position = hitPose.position;
}
}
}
static List<ARRaycastHit> s_Hits = new List<ARRaycastHit>();
ARRaycastManager m_RaycastManager;
}
Depending on your comments, if you are placing the object with the button, all you need to do right now is to disable this script that you have attached here. The object should not be moving since what causes its movement is this code bit in Update:
spawnedObject.transform.position = hitPose.position;
You can either comment out this part or deactivate the script, both should work fine.

How to make an enemy stop when he enter the required distance to shoot

The problem that i have is that when the enemy enters the range to shoot it stops and never follows the player again even if the player gets out of the shooting range. To detect if the player entered the shooting range I have made a sphere collider for the enemy.
using UnityEngine;
using System.Collections;
public class EnemyWithRifleMovement : MonoBehaviour {
private GameObject player;
private NavMeshAgent nav;
private bool playerInRange = false;
private Rigidbody rb;
void Awake()
{
rb = GetComponent<Rigidbody>();
player = GameObject.FindGameObjectWithTag("Player").gameObject;
nav = GetComponent<NavMeshAgent>();
}
void Update()
{
if(playerInRange)
{
nav.SetDestination(transform.position);
}
else if(playerInRange == false)
nav.SetDestination(player.transform.position);
}
void OnTriggerEnter(Collider other)
{
if(other.gameObject.CompareTag("Player"))
{
playerInRange = true;
}
}
void OnTriggetExit(Collider other)
{
if(other.gameObject.CompareTag("Player"))
{
playerInRange = false;
}
}
}
Your code looks all fine, except there is one typo. Replace OnTriggetExit with OnTriggerExit, and it should work!
Also, in my opinion it is easier to get the distance between the enemy and the player by doing playerInRange = (Vector3.Distance(transform.position, player) <= range.

Stop Player/User from multi jump in my Unity game

Hello and thanks for reading this post.
I'm new to Unity but regardless of this I managed to make a small 2d game. But I ran into a little problem with the jump function.
The player / user shouldn't be able to multi jump in the game.
This is the C# script that controls the player.
using UnityEngine;
using System.Collections;
public class RobotController : MonoBehaviour {
//This will be our maximum speed as we will always be multiplying by 1
public float maxSpeed = 2f;
public GameObject player;
//a boolean value to represent whether we are facing left or not
bool facingLeft = true;
//a value to represent our Animator
Animator anim;
//to check ground and to have a jumpforce we can change in the editor
bool grounded = true;
public Transform groundCheck;
float groundRadius = 0.2f;
public LayerMask whatIsGround;
public float jumpForce = 700f;
// Use this for initialization
void Start () {
//set anim to our animator
anim = GetComponent <Animator>();
}
void FixedUpdate () {
//set our vSpeed
anim.SetFloat ("vSpeed", rigidbody2D.velocity.y);
//set our grounded bool
grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);
//set ground in our Animator to match grounded
anim.SetBool ("Ground", grounded);
float move = Input.GetAxis ("Horizontal");//Gives us of one if we are moving via the arrow keys
//move our Players rigidbody
rigidbody2D.velocity = new Vector3 (move * maxSpeed, rigidbody2D.velocity.y);
//set our speed
anim.SetFloat ("Speed",Mathf.Abs (move));
//if we are moving left but not facing left flip, and vice versa
if (move > 0 && !facingLeft) {
Flip ();
} else if (move < 0 && facingLeft) {
Flip ();
}
}
void Update(){
//if we are on the ground and the space bar was pressed, change our ground state and add an upward force
if(grounded && Input.GetKeyDown (KeyCode.UpArrow)){
anim.SetBool("Ground",false);
rigidbody2D.AddForce (new Vector2(0,jumpForce));
}
}
//flip if needed
void Flip(){
facingLeft = !facingLeft;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
And here is the Player object and the GroundCheck Object.
How can I stop the player from being able to multijump. So if he press the upArrow key, He will jump and not be able to jump again before he lands.
Thanks for your time and help
Update
If its hard to see the Images here are the Image on Imgur:
http://imgur.com/GKf4bgi,2i7A0AU#0
You can add another Collider to your player GameObject and make it a trigger with Is Trigger option. Use this code to change a flag variable telling if player is on ground:
private bool isOnGround = false;
void OnCollisionEnter2D(Collision2D collision) {
isOnGround = true;
}
void OnCollisionExit2D(Collision2D collision) {
isOnGround = false;
}
Then you can allow jumping only when isOnGround is true.
You could make little game object called groundController, place it under player.
You're setting there bool value for grounded and in code your checking if your controller overlaps with ground.
watch it here for more info: http://youtu.be/Xnyb2f6Qqzg?t=45m22s