How do I pull a rigidbody towards the player using a raycasthit?,How do I add force to a rigidbody pulling that rigidbody towards my player using a RaycastHit
So basically I have a player with a gun that when I shoot it I want it to pull the target towards the player using a rigidbody. I have already tried putting in code to do this but I think I need to add a force to that rigidbody to pull it closer to the player which I can't find an answer. If this worked in my game I would have a gun that pulls the "target" towards the gun. Please help...
Heres what I've done so far:
public AudioSource blop;
public float damage = 10f;
public float range = 100f;
public Camera fpsCam;
public ParticleSystem flash;
public float cooldownTime = 2f;
private float nextFireTime = 0f;
void Update()
{
if (Time.time > nextFireTime)
{
if (Input.GetButtonDown("Fire1") && PauseMenu.GameIsPaused == false)
{
Shoot();
flash.Play();
blop.Play();
nextFireTime = Time.time + cooldownTime;
}
}
}
void Shoot()
{
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(damage);
}
}
}
Answer by streeetwalker · Apr 14, 2020 at 04:21 PM
@ELITEMASTER321, you don't need a RayCast for that. Just calculate:
Vector3 directionVector = (player.transform.position - enemy.transform.position).normalized;
That will give you the direction vector you can use with addForce to move the object toward the player.
Multiply it by what ever force factor you want to use to make a stronger or weaker force.