- Home /
Answered in comments
How to create a gravitational pull effect on object?
I am trying to make a black hole kind of obstacle in a 2D platformer I am working on. I will have to fine tune the forces and such.
But there is a problem. The effect only seems to apply in the Y axis.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(CircleCollider2D))]
public class BlackHoleScript : MonoBehaviour {
private float pullForce = 0.5f;
private float radius = 3f;
void Awake()
{
CircleCollider2D circleCollider2D= GetComponent<CircleCollider2D>();
radius = circleCollider2D.radius;
}
void OnTriggerStay2D(Collider2D other)
{
if (other.gameObject.tag == "Player")
{
float distance = Vector2.Distance(this.transform.position, other.gameObject.transform.position);
float force = pullForce * (radius / distance);
float x = this.transform.position.x - other.gameObject.transform.position.x;
float y = this.transform.position.y - other.gameObject.transform.position.y;
Debug.Log(x);
Debug.Log(y);
other.gameObject.rigidbody2D.AddForce(new Vector2(x*force, y*force), ForceMode2D.Impulse);
}
}
}
The x position of the object seems to be completely unaffected. What is it I am doing wrong?
http://wiki.unity3d.com/index.php/Gravity
You can put this script on your object and it will pull rigidbodies towards it like planetary gravity (or black hole).
Sorry for not helping with your current code, but I figured this might help so don't worry if you want to fix your own code ins$$anonymous$$d of using this.
Your code looks right, that's why I wondered what value you are getting for x in the Debug, you have written this in almost exactly the same way as I did for my whirlpools when I did those...
$$anonymous$$ake sure the rigidbody does not have the axis frozen.
How do you move your player on the x-axis? If you're setting the player's rigidbody's velocity's x-value in the movement script, that will effectively null out this script's effect on the velocity.
So if you have something like this in the player script:
rigidbody.velocity.x = Input.GetAxis("Horizontal");
That's the source of your problem.
Follow this Question
Related Questions
Problem with Wall Jump - 2D 0 Answers
knockback 3d c# 1 Answer
how can i put a aerial dashing script on my game? 0 Answers
issue with the rigid body x axis ,addforce doesn't work as it should for x axis 1 Answer
Jump higher when held button 1 Answer