Detecting touch on gameobject - c#

I want to detect a touch on a GameObject without sucess. My code copied from some examples is:
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Mouse Clicked!!");
Vector3 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 worldPoint2D = new Vector2(worldPoint.x, worldPoint.y);
RaycastHit2D hit = Physics2D.Raycast(worldPoint2D, Vector2.zero);
Debug.Log(hit.collider);
}
}
The output is always null :(
The game object is not moving and is a simple Cube with a box colider.

Try switching your Vector3 worldPoint into Vector2. So like this:
Vector3 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 worldPoint2D = new Vector2(worldPoint.x, worldPoint.y);
and then use worldPoint2D in the raycast.

Answering myself...I was not be able to resolve the question using Phisycs2D.Raycast method but Phisics.Raycast did the work:
void Update()
{
if (Input.GetMouseButtonDown(0))
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
Debug.Log(hit.collider);
}
}
}

Related

Raycast not detecting colliders

So I'm working on a little top-down perspective game and wanted to add a combat system. I set it up so that it'll shoot a raycast and if it hits an enemy they'll take damage but the raycast is returning nothing.
Vector3 mouse_pos = Input.mousePosition;
mouse_pos.z = 5.23f;
Vector3 objectPos = Camera.main.WorldToScreenPoint(transform.position);
mouse_pos.x = mouse_pos.x - objectPos.x
mouse_pos.y = mouse_pos.y - objectPos.y
if (Input.GetMouseButtonDown(0))
{
Raycast hit;
print(Physics.Raycast(transform.position, mouse_pos, out hit));
if (Physics.Raycast(transform.position, mouse_pos, out hit))
{
if (hit.collider.gameObject.name.Contains("enemy"))
{
hit.collider.gameObject.GetComponent<enemyMovement>().life -= 1;
}
}
}
The print returns false even when there's a gameobject there. It's probably a simple problem but I don't know what to do lol.
I changed the code for you, because I am not very familiar with the ray, thank you and hope it can help you.
void update(){
if (Input.GetMouseButtonDown(0))
{
// When the left mouse button is pressed, emit a ray to the screen
position where the mouse is located
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray,out hitInfo))
{
// When the ray collides with the object, draw the ray in the scene view
Debug.DrawLine(ray.origin, hitInfo.point, Color.red);
if (hitInfo.collider.gameObject.name.Contains("enemy"))
{
hitInfo.collider.gameObject.GetComponent<enemyMovement>().life -= 1;
}
}
}
}

NavMeshAgent first rotate to target direction and than move to it?

I'm making a small space game in 3D, but it looks awful when my ship is rotating in the middle of movement
So can someone please help me with code ? I need to rotate to that position and than move to it. (And i forgot to say, that rotation needs to be on Y axis)
Here is my code for that movement.
NavMeshAgent agent;
void Start()
{
agent = GetComponent<NavMeshAgent>();
}
void Update()
{
if(Input.GetMouseButton(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit) && hit.collider.tag == "Ground")
{
agent.SetDestination(hit.point);
}
}
}
You are supposed to stop the agents rotation.
this is the code:
NavMeshAgent agent;
void Start()
{
agent = GetComponent<NavMeshAgent>();
}
void Update()
{
if(Input.GetMouseButton(0))
{
agent.updateRotation = false;
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit) && hit.collider.tag == "Ground")
{
agent.SetDestination(hit.point);
}
}
}
And I also have a more efficient way for you to check if the player is on Ground.
Here is what you should do instead of
hit.collider.tag == "Ground
First, make a Layer named "Ground" (anything... depends on you).
Then, add a LayerMask in the script above the NavMeshAgent. public LayerMask groundLayer
And in the if statement
do this:
if (Physics.Raycast(ray, out hit, groundLayer))
{
agent.SetDestination(hit.point);
}
What this does is, it only considers the click on objects with the selected layer.The plus point here is that you can select multiple layers in the Inspector.
And do not forget to select the layer in the Inspector.
Thank you! <3

LineRenderer not drawing where Mouse clicks

Following a tutorial, I'm trying to use a grappling gun mechanic that utilizes a spring joint and Line Renderer.
I've got the line drawing upon mouseclick, but the end of the line is not drawing where the user clicks.
It looks like this:
Can anyone kind of help me out as to why it's not working? Here's the (wonky) project in action-
https://i.imgur.com/IuMsEsQ.mp4
Grappling gun code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GrapplingGun : MonoBehaviour
{
private LineRenderer lr;
private Vector3 grapplePoint; //where we grapple to
public LayerMask whatIsGrappable;
public Transform gunTip;
public Transform cam;
public Transform player;
private float maxDistance = 100f;
private SpringJoint joint;
void Awake()
{
lr = GetComponent<LineRenderer>();
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
StartGrapple();
}
else if (Input.GetMouseButtonUp(0))
{
StopGrapple();
}
}
void LateUpdate()
{
DrawRope();
}
void StartGrapple()
{
RaycastHit hit;
if (Physics.Raycast(cam.position, cam.forward, out hit, maxDistance, whatIsGrappable))
//if (Physics.Raycast(transform.position, Vector3.forward, out hit, maxDistance, whatIsGrappable))
{
grapplePoint = hit.point;
joint = player.gameObject.AddComponent<SpringJoint>();
joint.autoConfigureConnectedAnchor = false;
joint.connectedAnchor = grapplePoint;
float distanceFromPoint = Vector3.Distance(player.position, grapplePoint);
joint.maxDistance = distanceFromPoint * 0.8f;
joint.minDistance = distanceFromPoint * 0.25f;
joint.spring = 4.5f;
joint.damper = 7f;
joint.massScale = 4.5f;
lr.positionCount = 2;
}
}
void DrawRope()
{
//If not grappling, don't draw anything
if (!joint) return;
lr.SetPosition(0, gunTip.position);
lr.SetPosition(1, grapplePoint);
}
void StopGrapple()
{
lr.positionCount = 0;
Destroy(joint);
}
}
Thank you.
The underlying issue is your raycast. the second parameter is the direction of the ray, which you have as the camera direction. Currently your ray is pointing forward from the camera at all times as a result.
What you can do is use Camera.ScreenPointToRay to give a ray to cast along to give you a 3d mouse position to cast to, then use your current raycast but replace the second parameter with the direction from the player to the point hit by the raycast from the function mentioned before
Ray ray = Camera.ScreenPointToRay(Input.mousePosition);
Physics.Raycast(ray, out RaycastHit hit);
if (Physics.Raycast(transform.position, (hit.point - transform.position).normalized, out hit, maxDistance, whatIsGrappable)) {
// Your code here...
}

How to Click movement in unity and stop if there is Collider?

so I have an issue about movement click on unity it's about when I click of course the player will be moving to the position I clicked but, I don't want if I clicked on the wall and another button the player will be on the last mouse I clicked, I already add some collider but the player just bypass the collider so collider doesn't have any effect
the explanation
and this the script
[Header("Tweak")]
[SerializeField] Transform target;
Vector2 targetPos;
public float speed = 5f;
// Start is called before the first frame update
void Start()
{
targetPos = transform.position;
}
// Update is called once per frame
void Update()
{
Move();
}
public void Move()
{
if (Input.GetMouseButtonDown(0))
{
targetPos = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
if ((targetPos.x >= transform.position.x))
{
transform.localScale = new Vector2(.5f, .5f);
}
else
{
transform.localScale = new Vector2(-.5f, .5f);
}
target.position = targetPos;
}
if ((Vector2)transform.position != targetPos)
{
transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
}
}
You can do this using Raycast
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
if (hitInfo.collider.gameObject.tag == "Wall")
{
Debug.Log("tag");
//You can do what ever you want here.
}
}
}

How can I raycast between two moving objects in Unity?

How can I raycast between two moving objects?
I want to raycast from a moving enemy to a moving player. I dont know how to actually code to make the direction work.
using UnityEngine;
using System.Collections;
public class Enemy_Manage_Two : MonoBehaviour {
public GameObject player;
// Use this for initialization
void Start () { }
// Update is called once per frame
void Update () {
player = GameObject.FindGameObjectWithTag ("Player");
//Debug.Log (player.transform.position + " " + transform.position);
Ray ray = new Ray (transform.position, player.transform.position);
RaycastHit hit;
Debug.DrawRay (transform.position, player.transform.position,
Color.red);
if(Physics.Raycast(ray, out hit)) {
gameObject.renderer.material.color = Color.blue;
} else {
gameObject.renderer.material.color = Color.white;
}
}
}
Currently I haven't Unity so treat my answer as proof of concept.
//1. You have to calculate vector between enemy and player:
Vector3 direction=player.transform.position - transform.position;
direction.Normalize(); //Normalize vector
//2. Now you can create Ray
Ray ray=new Ray(transform.position,direction);

Categories

Resources