adding force toward specific object

hi…
this is my code :

rigidbody.AddForce(transform.forward * 1600);

I use this to add force that ball will go forward… but I want that add force to the the ball that it moves toward specific object… how can I do that?

Can u elaborate a bit more on this please.

rigidbody.AddForce((whateverObject.transform.position - transform.position) * someFactor * Time.smoothDeltaTime); There you go!

@sdgd - open a new question since the situation here appears to be different from your situation.

5 Answers

5

If you want the force to remain constant regardless of distance, use

rigidbody.AddForce((otherObject.transform.position - transform.position).normalized * forceAmount * Time.smoothDeltaTime)

It didn't work for me, it doesn't move. Would it still work for a Rigidbody2D?

Hi!

You can use transform.LookAt function to take rotation, then apply the force extracting vector from that rotate acquired, or simply rotate de ball with transform.LookAt and then apply forward force. You can see a good example in SmoothFollow script from Standard assets, perhaps may help you.

BR

alternative method which i prefer.

     transform.LookAt(target);
     rigidbody.AddRelativeForce(0, 0, power);

I ended up using:

void ACollisionBlackHole::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	// Fill set (unique)
	TSet<UPrimitiveComponent*> OverlapSet;
	SphereComp->GetOverlappingComponents(OverlapSet);

	for (UPrimitiveComponent* OtherOverlap : OverlapSet)
	{
		//UE_LOG(LogClass, Warning, TEXT("Blackhole : %s"), *OtherOverlap->GetName());
		FVector OverlapPosition = OtherOverlap->GetComponentTransform().GetLocation();
		FVector Direction = (GetActorLocation() - OverlapPosition).GetSafeNormal() * OtherOverlap->GetBodyInstance()->GetBodyMass() * DeltaTime * 100000;
		OtherOverlap->AddForce(Direction);
	}
}

public Transform objectToFollow;
private Rigidbody rb;

void Start(){
   rb = GetComponent<Rigidbody>();
}

void Update(){
   if(objectToFollow != null && Input.GetMouseButtonDown(0)){
       rb.AddForce(objectToFollow.forward * 1600f);
  }
}