Why doesn't my Raycasting work in Unity3d? - c#

My raycasting dosen't seem to work when i assign it max distance, and works fine with infinite distance.
Player is moving forward, and it touches the object but still no debug message. DrawRay draws a ray how its supose to.
void CastForwardRay()
{
int rayLength = 3;
RaycastHit hitInfo;
Ray ray = new Ray(rayCastTransform.position, rayCastTransform.forward);
Debug.DrawRay(rayCastTransform.position, rayCastTransform.forward * rayLength, Color.white);
if (Physics.Raycast(ray, out hitInfo, rayLength, playerLM))
{
if(hitInfo.collider.gameObject.tag == "Car")
{
print("hit a car");
}
}
}

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

Move object to mouse X

I have code for move object to mouse X, but this code does not count the distance(the object follows straight in the mouse) How could I get their kind of controls? Where the player moves positions between offsets instead of lerping to your finger position? Can you please help me?
private void HorizontalMovement()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
transform.position = Vector3.Lerp(transform.position, new Vector3(hit.point.x, transform.position.y, transform.position.z), speed * Time.deltaTime);
}
}
If I understand you correctly you want the movement stop at a certain distance before reaching the exact finger position.
// adjust that in the inspector
public float distanceOffset = 0.1f;
private void HorizontalMovement()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
// Get the direction from hit object to player
var direction = (new Vector3(transform.position.x - hit.point.x, 0, 0)).normalized;
// Add the offset in the direction to the hit position
var targetPosition = new Vector3(hit.point.x, transform.position.y, transform.position.z) + direction * distanceOffset;
transform.position = Vector3.Lerp(transform.position, targetPosition, speed * Time.deltaTime);
}
}

Unity Raycast always returning true

I have a character in Unity that I'm using a raycast to have him jump. But even when the raycast doesn't hit the ground (I can see the ray with the debug output) the player still can jump. Any ideas why the ray is always thinks it is colliding? Could the ray be hitting my character collider, causing it to be true? Ive been search online for hours and nothing I find is fixing the situation. Here is my code:
void FixedUpdate()
{
Ray ray = new Ray();
RaycastHit hit;
ray.origin = transform.position;
ray.direction = Vector3.down;
bool output = Physics.Raycast(ray, out hit);
Debug.DrawRay(ray.origin, ray.direction, Color.red);
if (Input.GetKey(KeyCode.Space) && output)
{
r.AddForce(Vector3.up * 1f, ForceMode.VelocityChange);
}
}
Could the ray be hitting my character collider?
Yes, that is possible.
This is actually problem that can easily be solve with Debug.Log.
Put Debug.Log("Ray Hit: " + hit.transform.name); inside the if statement and it will show what Object is blocking the Raycast.
If this is indeed the problem, this post describes many ways to fix it. That answer and code changes a little bit because this question is about 3D not 2D. Just use layer. Put your player in Layer 9 then the problem should go away.
void FixedUpdate()
{
int playerLayer = 9;
//Exclude layer 9
int layerMask = ~(1 << playerLayer);
Ray ray = new Ray();
RaycastHit hit;
ray.origin = transform.position;
ray.direction = Vector3.down;
bool output = Physics.Raycast(ray, out hit, 100f, layerMask);
Debug.DrawRay(ray.origin, ray.direction, Color.red);
if (Input.GetKey(KeyCode.Space) && output)
{
r.AddForce(Vector3.up * 1f, ForceMode.VelocityChange);
Debug.Log("Ray Hit: " + hit.transform.name);
}
}

How can i rotate the player according to mouse cursor position clicked?

void Update()
{
MovePlayer();
}
Then the first original MovePlayer i did rotate the player but in the specific angle i set for example:
private void MovePlayer()
{
if (Input.GetMouseButtonDown(0))
{
targetAngles = transform.eulerAngles + 85.0f * Vector3.up;
StartCoroutine(TurnObject(transform, transform.eulerAngles, targetAngles, smooth));
}
}
But i want it to rotate to the angle of the mouse cursor position clicked not to walk there or move there only to rotate and face to the mouse cursor position clicked. So i tried to change the MovePlayer method to this but this is wrong it does nothing:
private void MovePlayer()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
startPositon = hit.point;
targetAngles = transform.eulerAngles + 0 * Vector3.up;
StartCoroutine(TurnObject(transform, transform.eulerAngles, targetAngles, smooth));
}
}
}
And
IEnumerator TurnObject(Transform ship, Vector3 startAngle, Vector3 endAngle, float smooth)
{
float lerpSpeed = 0;
isSpinning = true;
while (lerpSpeed < 1)
{
ship.eulerAngles = Vector3.Lerp(startAngle, endAngle, lerpSpeed);
lerpSpeed += Time.deltaTime * smooth;
yield return null;
}
startPositon = ship.position;
isSpinning = false;
}
This is working but with some problems:
void Update()
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100000))
{
transform.LookAt(hit.point);
}
}
The first problem is when i point the mouse cursor to the sky since it's too far the player is not rotating and then when i point back to something in the distance range the player jump to the position. Not sure how to solve it. Maybe to calculate the sky(sky box in my case) distance so it will rotate also when pointing the sky ?
The second problem is when i point the mouse cursor on my self the player body it's making some fast rotations on place. How can i avoid it ? Or solve it ?
I tried to change the line:
if (Physics.Raycast(ray, out hit, 100000))
To
if (Physics.Raycast(ray, out hit))
But it didn't solve it. Maybe the problem is that my sky is a skybox i dragged to the Scene window so it's not an object.
My skybox is material i dragged to the Scene window so maybe this is the problem i can't rotate the player when the mouse cursor is pointing the sky. Any solution?

Categories

Resources