- Home /
Mouse aim raycast
Hi, I am trying to use the mouse to aim my raycast, its for a 2d platform game, it is working however is inaccurate, for example when I aim left it will shoot a bit higher than the mouse, I can instantiate objects with the mouse accurately in a test script but not aim accurately with raycast. Here is my code:
var distanceFromCamera = 5.0;
var distance = 10.0;
var prefabGrapple:Transform;
var xOffset = 0;
var yOffset = 0;
function Update ()
{
//on mouse click ...
if(Input.GetButtonDown("Fire1"))
{
var mousePosition = Input.mousePosition;
mousePosition.z = distanceFromCamera;
var worldMousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
worldMousePosition.x -= xOffset;
worldMousePosition.y -= yOffset;
var hit : RaycastHit;
if(Physics.Raycast(transform.position, worldMousePosition, hit, distance))
{
var InstanceGrapple = Instantiate(prefabGrapple, hit.point, Quaternion.identity);
Debug.Log(worldMousePosition);
if(Input.GetButtonDown("Fire2"))
{
Destroy(InstanceGrapple);
}
}
}
}
Also, how would I destroy the gameobject ?, the below code doesn't seem to destroy the game object.
Answer by DESTRUKTORR · Aug 01, 2012 at 07:24 PM
function Update ()
{
//on mouse click ...
if(Input.GetButtonDown("Fire1"))
{
var mousePosition = Input.mousePosition;
mousePosition.z = distanceFromCamera;
var worldMousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
worldMousePosition.x -= xOffset;
worldMousePosition.y -= yOffset; var hit : RaycastHit;
if(Physics.Raycast(transform.position, worldMousePosition, hit, distance))
{
impactPoint = hit.point;
var InstanceGrapple = Instantiate(prefabGrapple, hit.point, Quaternion.identity);
Debug.Log(worldMousePosition);
}
}
else if(Input.GetButtonDown("Fire2"))
{
Destroy(InstanceGrapple);
}
}
Try this, first. Your flow control statements (if statements) were all mashed together. I imagine you wanted them separate? You may want to look into standard formatting practices (such as separating lines at least at semicolons, and proper indenting). It would make it a lot easier to read and understand what you're doing wrong. However, you may want to try using a ray that casts from the player object to the mouse, in stead... since it would basically give you a precise trajectory, right away.
Answer by Will748 · Aug 01, 2012 at 11:23 PM
Omg all the formatting went completely wrong, the preview looked fine but has come out different (ill edit now), yeah what I have done is cast a ray from the player object and trying to cast it through the mouse, however always seems a bit off, the accuracy is also inconsistent e.g. sometimes by a 1 cm, sometimes by 0.5 cm.
Your answer
Follow this Question
Related Questions
Arrow not shooting the in right orientation 0 Answers
Use transform.LookAt with Raycast with a delayed bullet? 1 Answer
GameObject once walked on, gives message using C#? 1 Answer
Raycasting2D please help 1 Answer
how do i fix this small error 2 Answers