Unity raycast possible bug? - c#

this is my code for raycast in my school project game. If I put script on object everything is working just fine. But if I close Unity and reopen my project, the value of "jakDaleko" = distance stays locked on 1129.395 instead of changing every frame.
What should I change so it will work everytime and not just the first time ipress play button.
Here's my code.
script 1 = raycast
public class SmerDivani : MonoBehaviour {
public static float VzdalenostOdCile;
public float VzdalenostOdCileInterni;
// Update is called once per frame
void Update() {
RaycastHit Hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out Hit)) {
VzdalenostOdCileInterni = Hit.distance;
VzdalenostOdCile = VzdalenostOdCileInterni;
}
}
}
Second script
public class TabuleMesto1 : MonoBehaviour
{
public float JakDaleko;
public GameObject AkceTlacitko;
public GameObject AkceText;
public GameObject UIQuest;
public GameObject ThePlayer;
public GameObject NoticeCam;
void Update() {
JakDaleko = SmerDivani.VzdalenostOdCile;
}
void OnMouseOver() {
if (JakDaleko <= 5) {
AkceTlacitko.SetActive(true);
AkceText.SetActive(true);
}
if (JakDaleko > 5)
{
AkceTlacitko.SetActive(false);
AkceText.SetActive(false);
}
if (Input.GetButtonDown("Akce")) {
if (JakDaleko <= 5) {
AkceTlacitko.SetActive(false);
AkceText.SetActive(false);
UIQuest.SetActive(true);
NoticeCam.SetActive(true);
ThePlayer.SetActive(false);
}
}
}
void OnMouseExit() {
AkceTlacitko.SetActive(false);
AkceText.SetActive(false);
}
}

I'm not quite sure what you're trying to achieve? Maybe this should "fix" your problem, you're not clearing the distance if the raycast don't hits....
void Update() {
RaycastHit Hit;
if (Physics.Raycast(transform.position, transform.forward, out Hit)) {
VzdalenostOdCileInterni = Hit.distance;
}
else {
VzdalenostOdCileInterni = 0.0f;
}
VzdalenostOdCile = VzdalenostOdCileInterni;
}
Additionally I think you should use transform.forward instead of transform.TransformDirection(Vector3.forward)

I think that the biggest problem was the name of the file. For some reason, my stupidity included, the solution was to rename the script from table1 to table_1

Related

Unity - help needed to touch and hold UI button to call update method and auto fire (here is the script)

I am a newbie with no coding experience just started using unity I was following brackeys Ray cast shooting video,https://youtu.be/THnivyG0Mvo,, and I created the gun script but I wanted to turn it into mobile so I wanted to autofire by holding a UI button.
plz, I need help me know no code.
this is my code.
I was thinking is there a way to put something in place of input.getbutton to make a button that will autofire on holding.
Thanks & sorry if this is a silly question
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.VisualScripting;
public class Gun : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public float fireRate = 15f;
public float impactForce = 30f;
public Camera fpsCam;
public ParticleSystem muzzleFlash;
public GameObject impactEffect;
private float nextTimeToFire = 0f;
// Update is called once per frame
public void Update()
{
if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire)
{
nextTimeToFire = Time.time + 1f / fireRate;
Shoot();
}
}
public void Shoot()
{
muzzleFlash.Play();
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit,
range))
{
Enemy enemy = hit.transform.GetComponent<Enemy>();
if (enemy != null)
{
enemy.TakeDamage(damage);
}
if (hit.rigidbody != null)
{
hit.rigidbody.AddForce(-hit.normal * impactForce);
}
GameObject impactGO = Instantiate(impactEffect, hit.point,
Quaternion.LookRotation(hit.normal));
Destroy(impactGO, 2f);
}
}
}
Create a Button, and add a new script to it. This script will be responsible for handling the button state. Essentially what we need to do is..
When OnPointerDown happens, set a value to indicate the button is held down. When OnPointerUp happens, reset the value.
using UnityEngine;
using UnityEngine.EventSystems;
public class ClickAndHoldButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler
{
public bool IsHeldDown => isHeldDown;
private bool isHeldDown;
public void OnPointerDown(PointerEventData eventData)
{
isHeldDown = true;
}
public void OnPointerUp(PointerEventData eventData)
{
isHeldDown = false;
}
public void OnPointerEnter(PointerEventData eventData)
{
}
}
Then in Update of your gun, you will check the button state to see if it is being held down.
public ClickAndHoldButton mobileFireButton;
void Update()
{
if (Time.time >= nextTimeToFire && (
Input.GetButton("Fire1") ||
mobileFireButton.IsHeldDown))
{
nextTimeToFire = Time.time + 1f / fireRate;
Shoot();
}
}

Unity RTS style move object without navmesh agent

I'm trying to do RTS style movement with single selection only and without navmeshagent. When I click while another unit is already moving, its getting stopped and new one moving to same the point. Is there any way to seperate their hit points? Like I click to unit and order it to the point and then I click another unit and order him to another point.
Here is the video: demo
private Camera mycam;
private RaycastHit hit;
public Vector3 tf;
public LayerMask ground;
private bool move;
public static UnitMove instance;
private void Awake()
{
instance = this;
}
private void Start()
{
mycam = Camera.main;
}
private void Update()
{
if (Input.GetMouseButtonDown(1) && haveSelected())
{
if (UnitClick.Instance.selectChanged)
{
getMouseRay();
}
}
if (move)
{
SetDestination(UnitClick.Instance.selectedUnit.transform.position, hit);
}
}
private void SetDestination(Vector3 unitPos, RaycastHit hit)
{
move = true;
if (Vector3.Distance(UnitClick.Instance.selectedUnit.transform.position, hit.point) > 0.5f)
{
UnitClick.Instance.selectedUnit.transform.position = Vector3.MoveTowards(UnitClick.Instance.selectedUnit.transform.position,
new Vector3(hit.point.x, UnitClick.Instance.selectedUnit.transform.position.y, hit.point.z), 1f * Time.deltaTime);
}
}
public void getMouseRay()
{
Ray ray = mycam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, Mathf.Infinity, ground))
{
move = true;
}
}
private bool haveSelected()
{
if (UnitSelection.Instance.unitSelected.Count > 0)
{
return true;
}
else
{
return false;
}
}
}
Looks to me like rather than just setting a destination, the SetDestination() function actually moves UnitClick.Instance.selectedUnit every frame. Once you click another unit, UnitClick.Instance.selectedUnit presumably changes to the newly selected unit, meaning every object’s SetDestination() code is always moving the same single object.
You’ll want to do something like save the destination in an instance variable when SetDestination() is first called and then have the move code change either:
change transform.position if the script is attached to the object you want to move
or if not: save the current UnitClick.Instance.selectedUnit in an instance variable when SetDestination() is first called and then change its position in the move code.
Edit: Here’s an attempt to show what I mean but note that this assumes the script is attached to the GameObject you want to move. It also preserves your existing system of setting the destination every frame while the unit is selected (it may be more desirable to update it only when the mouse is clicked?)
private Camera mycam;
private RaycastHit hit;
public Vector3 tf;
public LayerMask ground;
private bool move;
private Vector3 destination;
public static UnitMove instance;
private void Awake()
{
instance = this;
}
private void Start()
{
mycam = Camera.main;
}
private void Update()
{
if (Input.GetMouseButtonDown(1) && haveSelected())
{
if (UnitClick.Instance.selectChanged)
{
getMouseRay();
}
}
if (move)
{
if( transform == UnitClick.Instance.selectedUnit.transform ) // If we are currently selected
SetDestination(/*UnitClick.Instance.selectedUnit.transform.position,*/ hit); // Update our destination
// If ‘move’ is true, move towards our destination whether or not we are currently selected
if (Vector3.Distance(transform.position, destination) > 0.5f)
transform.position = Vector3.MoveTowards(transform.position, destination, 1f * Time.deltaTime);
else
move = false; // This part is a guess at what you want — remove if it causes problems.
}
}
private void SetDestination(/*Vector3 unitPos,*/ RaycastHit hit)
{
move = true;
destination = new Vector3(hit.point.x, transform.position.y, hit.point.z);
}
public void getMouseRay()
{
Ray ray = mycam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, Mathf.Infinity, ground))
{
move = true;
}
}
private bool haveSelected()
{
if (UnitSelection.Instance.unitSelected.Count > 0)
{
return true;
}
else
{
return false;
}
}

Retrive objects from a list and teleport them to a specific location in Unity

and thank you for looking at this in advance.
I have yet another problem that i need to solve and it goes like this:
I have a list of objects that i select with a raycast, and i would like to teleport them to a specific location in the scene. Like for example i have selected a cube and a sphere and they are added to my list called playersTagged.
How can i get the objects in my list to that specific location when OnCollisionEnter with my player that has the tag "Tagger"?
My code looks like this:
PlayerTagged Class
using System.Collections.Generic;
using UnityEngine;
public class PlayerTagged : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public Camera fpsCam;
public List<GameObject> playersTagged;
private void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if (target != null && target.isHit == false)
{
target.takeDamage(damage);
if(hit.collider.tag == "Taggable")
playersTagged.Add(hit.collider.gameObject);
target.isHit = true;
}
}
}
}
Teleport class:
using UnityEngine;
public class Teleport : MonoBehaviour
{
public Transform teleportTarget;
public PlayerTagged player;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Tagger")
{
Debug.Log("You hit the can");
}
}
}
You need to have the PlayerTagged reference in your Teleport component. If both objects will always exist in your scene, only create a public field in your Teleport and drag and drop your PlayerTagged ref, otherwise you will need to fill this ref by code using some "find" approach, for example, GameObject.FindObjectWithTag().
You can also make an event that trigger when the object that entered the OnTriggerEnter is valid (I mean, when your tag condition pass) and then make sure that PlayerTagged is being registered as listener to this event.
First one is easier to setup, but if you plan to make unique things with this OnTriggerEnter as playing sounds, changing data or something like that, the second one is a better approach.
EDIT: I'll try to insert some code, let me know if you still having problems on getting the idea
"If both objects will always exist in your scene..."
using UnityEngine;
public class Teleport : MonoBehaviour
{
public Transform teleportTarget;
public PlayerTagged player; // I didn't saw that you already have an ref here, my bad, so you only need to access the fields
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Tagger")
{
Debug.Log("You hit the can");
var list = player.playersTagged; // this is how you will access your list
// Do some stuff with your list
}
}
}
Ignore the rest, it will only complicate things
EDIT 2: Making the teleport happen in player, and teleport every object
using System.Collections.Generic;
using UnityEngine;
public class PlayerTagged : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public Camera fpsCam;
public List<GameObject> playersTagged;
private void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
// Option 1:
private void OnTriggerEnter(Collider col)
{
if (col.gameObject.tag == "Teleport Tag")
{
var teleport = col.gameObject.GetComponent<Teleport>();
TeleportObjectsTo(teleport.teleportTarget.position);
}
}
void Shoot()
{
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if (target != null && target.isHit == false)
{
target.takeDamage(damage);
if(hit.collider.tag == "Taggable")
playersTagged.Add(hit.collider.gameObject);
target.isHit = true;
}
}
}
public void TeleportObjectsTo(Vector3 targetPosition)
{
foreach(taggedObjects in playersTagged)
{
taggedObjects.transform.position = targetPosition;
}
}
}
You can also make the teleport happen on teleport script:
using UnityEngine;
public class Teleport : MonoBehaviour
{
public Transform teleportTarget;
public PlayerTagged player; // I didn't saw that you already have an ref here, my bad, so you only need to access the fields
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Tagger")
{
Debug.Log("You hit the can");
// Option 2:
player.TeleportObjectsTo(teleportTarget);
// Option 3: Or you can iterate here instead of make use of the API
foreach(var taggedObjects in player.playersTagged)
{
taggedObjects.transform.position = targetPosition;
}
}
}
}
Chose one option, and delete/comment others
--N

My script doesn't activate UI and doesn't play animations

Hey guys I have a made two scripts to handle door opening.
Script 1 - Raycast
Script 2 - The door opening script
I have the raycast on the player camera and I have script 2 on the door.
But there is a problem.
In script 2, I have code that makes UI active and inactive and code that does the door animation
SCRIPT 1 -
using System.Collections.Generic;
using UnityEngine;
public class PlayerCasting : MonoBehaviour
{
public Camera FPScam;
public float range = 6;
public static float ToTarget;
void Update()
{
RaycastHit Hit;
if (Physics.Raycast(FPScam.transform.position, FPScam.transform.forward, out Hit, range))
{
ToTarget = Hit.distance;
}
}
}
SCRIPT 2 -
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DoorOpen : MonoBehaviour
{
public float Distance;
public GameObject key;
public GameObject reason;
public GameObject Hinge;
public AudioSource DoorCreak;
// Update is called once per frame
void Update()
{
Distance = PlayerCasting.ToTarget;
}
private void OnMouseOver()
{
if (Distance <= 3.5f)
{
key.SetActive(true);
reason.SetActive(true);
}
if (Input.GetButtonDown("Action"))
{
if (Distance <= 3.5f)
{
key.SetActive(false);
reason.SetActive(false);
this.GetComponent<BoxCollider>().enabled = false;
Hinge.GetComponent<Animation>().Play("DoorOpenAnim");
DoorCreak.Play();
}
}
}
private void OnMouseExit()
{
key.SetActive(false);
reason.SetActive(false);
}
}
But, the UI doesn't activate nor does the animation plays when I click 'E' and when the Raycast distance <= 3.5.
I have the raycast on the player camera
Since you're using OnMouseOver() and OnMouseExit() your methods will only work when the player's mouse is on the thing you want to raycast.
Make sure that the raycast is actually pointing the same direction the mouse cursor is. You use use Debug.Raycast() to visually see where the raycast is going.
If the raycast is going in the direction you want it to and it's still not working try a different way of communicating through the scripts and avoid using OnMouseOver().
For example you could try something like this:
public class PlayerCasting : MonoBehaviour
{
public Camera FPScam;
public float range = 6;
public static float ToTarget = 0f;
public static GameObject HoveredObject = null; // <----
void Update()
{
RaycastHit Hit;
if (Physics.Raycast(FPScam.transform.position, FPScam.transform.forward, out Hit, range))
{
ToTarget = Hit.distance;
HoveredObject = Hit.collider.gameObject; // <----
}
}
}
public class DoorOpen : MonoBehaviour
{
public float Distance;
public GameObject key;
public GameObject reason;
public GameObject Hinge;
public AudioSource DoorCreak;
// Update is called once per frame
void Update()
{
if (PlayerCasting.HoveredObject == gameObject)
{
Distance = PlayerCasting.ToTarget;
CheckDistance();
}
}
private void CheckDistance()
{
if (Distance <= 3.5f)
{
key.SetActive(true);
reason.SetActive(true);
if (Input.GetButtonDown("Action"))
{
key.SetActive(false);
reason.SetActive(false);
this.GetComponent<BoxCollider>().enabled = false;
Hinge.GetComponent<Animation>().Play("DoorOpenAnim");
DoorCreak.Play();
}
}
else
{
key.SetActive(false);
reason.SetActive(false);
}
}
private void OnMouseExit()
{
key.SetActive(false);
reason.SetActive(false);
}
}

Bullet not going towards target

Not sure why, I've done this sort of this a bunch of times, but this is giving me some issues. Making a project for Game AI, I have a whole bunch of stuff already done, now just making some turrets that if the player is in a certain range it will fire, which I have already. The turret fires the bullet and then for some reason they just start destroying themselves and they don't go towards my player. Wondering if anyone on here can help, thanks in advance!
Some details you may need to know:
I have a Base, a Gun nose and a Gun for my turret. My Gun has a GunLook.cs script that makes it look at the player (so when they shoot it should go towards them), I'm not sure if that has anything to do with why I'm having these issues, but I'll post that code as well just incase
How my Hierchy for my turret is
Turret_AI (Base)
Gun (child of Turret_AI)
bulletSpawn (child of Gun)
Gun_Nose (child of turret_AI)
bulletSpawn is an empty GameObject I created in hopes to solve my problem. I set it just off the Gun so that it wouldn't just collide with gun and destroy itself (what I thought it might be doing, but not correct).
That should be all the info needed, if anyone needs more I will be checking this every 2 seconds so let me know and I will get back to you with quick response.
TurretScript.cs
(I did set the GameObject to Player in Unity, before anyone asks)
using UnityEngine;
using System.Collections;
public class TurretScript : MonoBehaviour {
[SerializeField]
public GameObject Bullet;
public float distance = 3.0f;
public float secondsBetweenShots = 0.75f;
public GameObject followThis;
private Transform target;
private float timeStamp = 0.0f;
void Start () {
target = followThis.transform;
}
void Fire() {
Instantiate(Bullet, transform.position , transform.rotation);
Debug.Log ("FIRE");
}
void Update () {
if (Time.time >= timeStamp && (target.position - target.position).magnitude < distance) {
Fire();
timeStamp = Time.time + secondsBetweenShots;
}
}
}
GunLook.cs
// C#
using System;
using UnityEngine;
public class GunLook : MonoBehaviour
{
public Transform target;
void Update()
{
if(target != null)
{
transform.LookAt(target);
}
}
}
BulletBehavior.cs
using UnityEngine;
using System.Collections;
public class BulletBehavior : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (rigidbody.velocity.magnitude <= 0.5)
Destroy (gameObject);
}
void OnCollisionEnter(Collision collision)
{
if (collision.collider)
{
if(collision.gameObject.tag == "Enemy" || collision.gameObject.tag == "EnemyProjectile")
{
Physics.IgnoreCollision(rigidbody.collider,collision.collider);
//Debug.Log ("Enemy");
}
if(collision.gameObject.tag == "SolidObject")
{
Destroy(gameObject);
}
if(collision.gameObject.tag == "Player")
{
Destroy(gameObject);
}
}
}
}
You're never moving your bullet.
public class BulletBehavior : MonoBehaviour
{
private const float DefaultSpeed = 1.0f;
private float startTime;
public Vector3 destination;
public Vector3 origin;
public float? speed;
public void Start()
{
speed = speed ?? DefaultSpeed;
startTime = Time.time;
}
public void Update()
{
float fracJourney = (Time.time - startTime) * speed.GetValueOrDefault();
this.transform.position = Vector3.Lerp (origin, destination, fracJourney);
}
}
Then call it like so:
void Fire()
{
GameObject bullet = (GameObject)Instantiate(Bullet, transform.position , transform.rotation);
BulletBehavior behavior = bullet.GetComponent<BulletBehavior>();
behavior.origin = this.transform.position;
behavior.destination = target.transform.position;
Debug.Log ("FIRE");
}
Note: If you're trying to mix this approach with trying to use physics to move the bullet you may end up with strange results.

Categories

Resources