- Home /
Pulling Objects to Player using force
Let’s say that I have a Player, and my player can walk, run, and jump. Also, my player has a Polygon Collider 2D and if 2D GameObjects( with a Rigidbody2D and Box Collider 2D) are detected in the Polygon Collider 2D the Player will Add Force to movable 2D GameObjects that are in the Polygon Collider 2D to be pulled towards the Player. So I used a Polygon Collider for my Player and a Box Collider for the 2D GameObject that the Player’s Polygon Collider is supposed to pull towards the Player, but I ran into some problems. So the Players Polygon Collider(that is a rectangular shape) that reaches out from the Players right side. Instead of pulling the 2D GameObject towards the Player when it’s in the Players Polygon Collider, the 2D GameObject Box Collider collides with the Players Polygon Collider, now let me explain the position of the Player and 2D GameObject. Now the Player and GameObject are on the middle of a platform, so the Player is on the left side of the Scene screen and the GameObject is on the right, okay now when the Player’s Polygon Collider collides with the 2D GameObject Box Collider the Player is instantly moved to the right by 20 and moved up by 25, and I know it has something to do with this line of code, Rigid.AddForce(new Vector2(20, 25)); .I then decided to try to figure out what happened, so I change the Rigid.AddForce(new Vector2(20, 25)); to Rigid.AddForce(new Vector2(-1, 0)); .Now when the colliders collide it pushes the Player back while leaving the the 2D GameObject in the same position, then I tried Rigid.AddForce(new Vector2(0, 1)); even when the Player Polygon Collider isn’t colliding with the 2D GameObject Box Collider it forces the player into the air, but he eventually comes back down, but the Player falls through the platform.
-By the way, the Player is named “Indingo” in this Unity2D project and so is it’s Tag. Also, the mass of Indingo and the 2D GameObject is 0 with a gravity scale of 1.
Here’s my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Indingo_Vacuum_Mouth : MonoBehaviour
{
private Rigidbody2D Rigid;
public float vacuumForce;
// Use this for initialization
void Start()
{
Rigid = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag != “Player”)
{
Rigid.AddForce(new Vector2(20, 25));
//Do something
}
}
}
Your answer
