- Home /
Objects stop, but then pass through eachother, Rigidbody2D
I'll give the code for both of my objects, but essentially what happens is one object will collide with the other, and then they'll pass through each other. I think the problem is that I'm coding their movement incorrectly, but it could be one of the rigidbody settings. I think it should be an easy fix, but I couldn't find the solution online anywhere... Here's the inspector settings on the "ball" object (a square): Here's the inspector settings on the "Obstacle" object (a big rectangle):
Here's my code for the ball and the obstacle:
Ball
using UnityEngine; using System.Collections;
public class Falling : MonoBehaviour {
Vector3 velocity = Vector3.zero;
public Vector3 gravity;
public Rigidbody2D rb;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame, PHYSICS here
void FixedUpdate () {
velocity += gravity * Time.deltaTime;
rb.AddForce(transform.position += velocity * Time.deltaTime);
}
}
Obstacle
using UnityEngine; using System.Collections;
public class Upward : MonoBehaviour {
Vector3 velocity = Vector3.zero;
public Vector3 AntiGravity;
public Rigidbody2D rb;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D>();
float RandomFl = Random.Range(-0.755f, 0.755f);
transform.position = new Vector3 (RandomFl, -3.4f, -1f);
}
// Update is called once per frame
void Update () {
if (transform.position.y <= 3.35) {
velocity -= AntiGravity * Time.deltaTime;
rb.AddForce(transform.position -= velocity * Time.deltaTime);
}
}
}
If you guys could help me, that would be awesome! I can't find the solution online.
Wow, I see lots of weird stuff here...
First why increment your velocity every FixedUpdate()... and why multiply it by Time.deltaTime knowing you are in fixedUpdate? Then why in your AddForce you pass an assignment? (-= or += are assignments)
I'd also say the AddForce is the problem in both cases. Just use the velocity as a force, one positive, one negative, NOT the position too. Assume your game is not running around the world's zero but rather somewhere around the hundreds. Do you want to use THAT position as the new force to move by?
Alright guys, I see what you mean. I should just be using the built in physics, I'm not sure what I was thinking with making my own. Thanks, I guess this can be considered answered.
For the record this is how you use gravity when you need your own:
Vector3 gravity = new Vector3(0,-20,0);
void FixedUpdate()
{
rb.AddForce(gravity, Force$$anonymous$$ode.Acceleration);
}