Home > other >  How to make a game object move to the opposite direction of a constantly moving object? Unity 2D
How to make a game object move to the opposite direction of a constantly moving object? Unity 2D

Time:07-27

I have a game object that constantly rotates around another one: enter image description here

What I am trying to achieve is to have the circle move in the opposite direction of the square when I press the space key, the square will simulate a propeller, for example:

enter image description here

This is the code I have, which kinda works:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class PlayerController : MonoBehaviour
 {
 
     [SerializeField] GameObject rotatingPropellant;
     [SerializeField] float rotationSpeed;
     [SerializeField] float impulseForce;
 
 
     Rigidbody2D playerRb;
 
     void Start()
     {
         playerRb = GetComponent<Rigidbody2D>();
     }
 
     void Update()
     {
         RotatePropellant();
         Move();
     }
 
     void RotatePropellant()
     {
         rotatingPropellant.transform.RotateAround(transform.position, new Vector3(0f, 0f, 1f), rotationSpeed * Time.deltaTime);
     }
 
     void Move()
     {
         if (Input.GetButtonDown("Jump"))
         {
             playerRb.velocity = -rotatingPropellant.transform.position * impulseForce * Time.deltaTime;
         }
 
     }
 }

But sometimes the circle moves up even if the square is up (meaning that the circle should be pushed down), not sure if maybe the signs are not correct or if I should be approaching this with a different method

CodePudding user response:

To get movement direction, you can use this vector formula AB = B - A. This formula will give you the position vector of A Related to B space and if you normalize this vector you will get the movement direction

A is sphere and B is Square at here. Check Vector Addition and Substraction.

CodePudding user response:

So this:

playerRb.velocity = -rotatingPropellant.transform.position * impulseForce * Time.deltaTime;

relies on rotatingPropellant position relative to World's zero position (Vector3.zero), which might work only if the propellant revolves around this zero point. What you should probably do instead is get the difference:

Vector3 dir = (rotatingPropellant.transform.position - transform.position).normalized;
playerRb.velocity = dir  * impulseForce * Time.deltaTime;

Also, instead of changing velocity, you can add force instead:

Vector3 dir = (rotatingPropellant.transform.position - transform.position).normalized;
playerRb.AddForce(dir  * impulseForce, ForceMode2D.Impulse);
  • Related