- Home /
Raycast Trouble
Okay I am trying to make this voxel based game (Not a minecraft clone its a fast-paced combat game). Though I just want to add this small part to the game which is breaking and placing cubes. Yep! That works fine but when I look down at my feet and I right-click (Break) I can destroy my player also I have to move far back to place a block or it will place it where my player is.
All I have is a camera (Break script is here) and a pickaxe parented to the camera so it looks like I'm breaking blocks with a tool.
Heres my break script:
#pragma strict
var blockLayer : LayerMask = 1;
var range : float = Mathf.Infinity;
var hit : RaycastHit;
function Update () {
if (Input.GetMouseButtonDown(1)) Build();
if (Input.GetMouseButtonDown(0)) Erase();
}
function Build() {
if (HitBlock()) {
var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = hit.transform.position + hit.normal;
}
}
function Erase() {
if (HitBlock())
Destroy(hit.transform.gameObject);
}
function HitBlock() : boolean {
return Physics.Raycast(transform.position, transform.forward, hit, range, blockLayer);
}
Thanks in advance!
I'm not sure what you are asking us to help you with. Are you asking for help because your character is being destroyed? If so, are you sure that your character is not on the block layer? If you look in the inspector, are you sure that the 'blockLayer' is set to only the block layer? Layer 1 (your initialization of 'blockLayer'). Is the 'Default' layer. Note primitive cubes are not Voxels.
Answer by morbidcamel · Jan 12, 2014 at 11:39 AM
Hi this might help - use the Input.mousposition
return Raycast(Input.mousePosition, out info);
}
private bool Raycast (Vector3 screenPoint, out RaycastInfo info)
{
Ray ray = camera.ScreenPointToRay (screenPoint);
return PhysicsUtil.Raycast(ray, out info, raycastDistance);
}
Use the scene camera and then use ScreenPointToRay to create a Ray instance to pass to the ray cast. It means it will cast a ray from the mouse position into world space and is the most accurate way to obtain a Raycast from where you pointing at...
Sorry if you confused with PhysicsUtil that is just a wrapper class I wrote to first test some common collider before doing a Physics,Raycast on every collider in the scene.
Your answer
Follow this Question
Related Questions
No-Break/Non-Breaking Space in Strings 3 Answers
How to make mecanim animation stay at player's position 3 Answers
Dual Slider / Min Max Slider for GUI 2 Answers
My gun wont stay in the same spot 2 Answers