- Home /
RayCast Problem : 2d
I am making space shooter kind of scene. But in that i am shooting in the direction of mouse position.
All this works fine. i am having Enemy script like this:
function Start () {
SetPositionandSpeed();
}
function Update () {
var amttomove : float = currentSpeed * Time.deltaTime;
transform.Translate(Vector3.down * amttomove);
if(transform.position.y <= -6.00f)
{
SetPositionandSpeed();
}
}
function SetPositionandSpeed()
{
currentSpeed = Random.Range(minSpeed , maxSpeed);
x = Random.Range(-4.00f , 4.00f);
z = -6.72f;
y = 8.0f;
transform.position = new Vector3(x , y , z);
}
On mousebutton down I am Generating Bullet.
And my shooting script is this :
function Update ()
{
var bullet : GameObject = GameObject.Find("Bullet");
var hit : RaycastHit ;
var ray : Ray = Camera .main .ScreenPointToRay (Input.mousePosition );
if(Physics.Raycast (ray, hit)){
target = (hit.point - bullet.transform.position).normalized;
}
if(target != null){
var moveAmount : float = 6 * Time.deltaTime;
transform.Translate(target * moveAmount);
}
if(transform.position.y >= 7.0f)
{
Destroy(gameObject);
}
}
But sometimes when my mouse position comes over the enemy , my bullet changes direction slightly.. So what do i need to do? May be Problem with RayCast..
Please Help me to solve out my problem..
Thanks for your support and help in advance..
Answer by hexagonius · Apr 01, 2013 at 11:43 AM
Does "target" have an initial value like Vector3.up, because since there's only one Translation method it has to, otherwise the bullet won't move at all, right? In line 5 you do a raycast. Since there's not much to raycast at, everything from line 9 - 12 is executed only when you mouseover something. I bet that could be enemies or bullets. And since you do a calculation for a new direction Vector from bullet to enemy when pointing an enemy, of course it will move towards it.
The part where you instantiate the bullet is missing, but if this second script is attached to your player I would recommend, for object oriented purposes, move it to your Bulletprefab. Bullets should be able to move by themselves instead of being looked up every Update() from another script and pushed around.
Another question is: If you don't want the bullet to fly towards enemies when the mouse points on them, why do you have the raycast in there?
Your answer
Follow this Question
Related Questions
Bullet Effect 2 Answers
Bullet Shoot with RayCast don't destroy onCollisionEnter 1 Answer
Fire Bullet To Mouse Position Problem 2 Answers
Destroy Projectile on collision 3 Answers
Why won't my bullets detect a collision and be destroyed?... 4 Answers