Hey! I was wondering how to get an object to move where the raycast ends or hits a collider. What I want to do is instantiate a bullet that always goes where the player shoots (so to check where that is, using RayCast). Anybody know how to do that? A script example would be much appreciated!
This could be the bullet script:
Vector3 endPoint = Vector3.zero;
float speed = 50f;
void SetEndPoint(Vector3 p)
{
endPoint = p;
}
void Update()
{
if(endPoint != Vector3.zero)
transform.position = Vector3.MoveTowards(transform.position, endPoint, Time.deltaTime * speed);
}
Where you create the bullet you get a reference to it and send it the SetEndPoint function:
Transform bullet = Instantiate(...);
bullet.SendMessage("SetEndPoint", hit.point);
Furthure more if you are shooting at objects that might get destroyed, you could also send that object’s reference to the bullet too, by adding a variable and a function for it:
Transform enemy;
void SetEnemy(Transform e)
{
enemy = e;
}
Then you should add a direction variable for the enemy direction, so if the enemy is dead before the bullet hits him, it continues in the same direction:
Vector3 enemyDirection;
void Start()
{
enemyDirection = (enemy.position - transform.position).normalized;
}
And you would add to the Update:
void Update()
{
if(endPoint != Vector3.zero)
transform.position = Vector3.MoveTowards(transform.position, endPoint, Time.deltaTime * speed);
if(enemy)
transform.position = Vector3.MoveTowards(transform.position, enemy.position, Time.deltaTime * speed);
else
transform.position += enemyDirection * Time.deltaTime * speed;
}