- Home /
Help with casting a raycast C#
Hello,
I have a game where a block moves and the player has to navigate it through gates. The script I'm using uses transforn.translate
to move the cube forward and sideways. But now it has no colliders because that method ignores them. The solution is to use a raycast. I have no idea how to do this though, I can't get it to work. Can someone give the proper code? Thanks you.
my code:
using System.Collections;
public class testMotor
: MonoBehaviour {
public float MoveSpeed = 40;
public float SideSpeed = 10;
void Update ()
{
float MoveForward = MoveSpeed * Time.deltaTime;
float MoveSide = Input.GetAxis("Horizontal") * SideSpeed * Time.deltaTime;
transform.Translate(Vector3.forward * MoveForward);
transform.Translate(Vector3.right * MoveSide);
}
}
What are you trying to solve with a Raycast? Are you trying to simulate collisions?
Yes, the gates need to detect when the cube gets through and also if it's the right one. And when the cube has reached the end of the track it needs to go to the next level. And to prevent it from going off the course and out of camera sight.
Sounds like you could also solve this with checking rect/boundaries and or triggers in the gates. If you are looking for collisions and ai try a navmesh agent possibly. Hard to tell the best solution from this. Also you probably want colliders on gates and boxes if there aren't too many of them. If there are then you'll have to shoot a ray out of each side however you will again need colliders for this.
Answer by drawcode · May 27, 2013 at 02:24 PM
C#
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
void Update() {
Vector3 fwd = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(transform.position, fwd, 10))
print("There is something in front of the object!");
}
}
Distance based
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
void Update() {
RaycastHit hitForward;
RaycastHit hitBack;
RaycastHit hitLeft;
RaycastHit hitRight;
// forward
if (Physics.Raycast(transform.position, Vector3.forward, out hitForward)) {
float distanceForward = hitForward.distance;
}
// back
if (Physics.Raycast(transform.position, -Vector3.forward, out hitBack)) {
float distanceReverse = hitBack.distance;
}
// left
if (Physics.Raycast(transform.position, Vector3.left, out hitLeft)) {
float distanceLeft = hitLeft.distance;
}
// right
if (Physics.Raycast(transform.position, Vector3.right, out hitRight)) {
float distanceRight = hitRight.distance;
}
}
}
Your answer
Follow this Question
Related Questions
Dashing through enemies, but not walls. 1 Answer
Transform.Position Collision Issue 0 Answers
AttackDammage errors 1 Answer
Raycast from camera not hitting Terrain 1 Answer
Move until collision sticks 0 Answers