2D Collision detection not working - c#

I've been trying to get collision to work but so far no good.
Screenshot Unity
This is my moveBall.cs which I put on my Ball Object.
using UnityEngine;
using System.Collections;
public class moveBall : MonoBehaviour {
float balSnelheid = 1;
void Update () {
transform.Translate (0, balSnelheid * Time.deltaTime, 0);
}
void OnCollisionTrigger2D (Collision2D coll) {
if (coll.gameObject.name == "Brick") {
Destroy(coll.gameObject);
}
}
}
And this is my movePlayer.cs which I put on my Player Object.
using UnityEngine;
using System.Collections;
public class movePlayer : MonoBehaviour {
public float snelheid;
// Use this for initialization
void Start () {
Screen.showCursor = false;
}
// Update is called once per frame
void Update () {
if (transform.position.x + Input.GetAxis ("hor") * snelheid * Time.deltaTime < 2.9) {
if (transform.position.x + Input.GetAxis ("hor") * snelheid * Time.deltaTime > -2.9) {
transform.Translate(Input.GetAxis("hor") * snelheid * Time.deltaTime, 0, 0);
}
}
if (transform.position.x + Input.GetAxis ("hor") * snelheid * Time.deltaTime > 3) {
transform.position = new Vector3(2.9f, -4.7f, 0);
} else if (transform.position.x + Input.GetAxis ("hor") * snelheid * Time.deltaTime < -3) {
transform.position = new Vector3(-2.9f, -4.7f, 0);
}
}
}
If anyone could give me a tip/solution it would help me out a lot!

One issue I see right off the bat is that you are using the RigidBody component rather than the RigidBody2D component. You need to be careful which components you use.
Also, OnTriggerEnter2D() or OnCollisionEnter2D() is what you are looking for, not OnCollisionTrigger2D.
If using the the 3d components was by choice, please look at OnCollisionEnter() or OnTriggerEnter()

Related

unity c# issue unable to get perfect position of a enemy in unity c# script using transform.position

when I command or set an enemy to go left and then at reaching a particular state or position i say my enemy to go right but it is not going right and not reaching to perfect position here is the code I think there is no issue in the code but it is not working properly so here are some images of the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enem : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.position = transform.position + new Vector3(-3f, 0f, 0f)* 1 * Time.deltaTime;
if (transform.position.x > -29)
{
transform.position = transform.position + new Vector3(3f, 0f, 0f) * 1 * Time.deltaTime;
}
}
}
Before adding any bool logic, try first simply moving your element:
using UnityEngine;
public class SimeMoveMove : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
transform.position += new Vector3(3f, 0f, 0f);
}
}
}
I smiled a little the moment I understood what you were trying to do.
I wrote the code imagining the result you were trying to make!
Create a cube, attach this code as component, and run the game.
// Gift for you friend
public class MoveTest : MonoBehaviour
{
private int _direction = 1;
void Start()
{
transform.position = Vector3.zero;
}
void Update()
{
Vector3 position = transform.position;
int direction = ShouldWeSwitchDirection(position.x, 0f);
if (direction != 0)
{
_direction = direction;
}
transform.position += _direction * new Vector3(3f, 0f, 0f) * 3f * Time.deltaTime;
}
private int ShouldWeSwitchDirection(float value, float center = 0f)
{
float direction = Mathf.Sign(value - center);
float distance = Mathf.Abs(value - center);
// If X Position is larger than 29
if (Mathf.Abs(distance) > 29)
{
// If X is on right side
if (direction >= 0)
{
return -1;
}
// If X is on left side.
else
{
return 1;
}
}
else
{
return 0;
}
}
}

Unity AI character controller gravity

I am trying to add gravity to my "residents" of a town builder game. Basically the residents just walk around to a random location, wait 2 seconds then do it again. I am trying to add gravity to them so they don't float.
controller = GetComponent<CharacterController>();
moveDirection = Vector3.zero;
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
These four lines are the gravity lines I tried added and very weird things happen such as the resident teleporting up if it touches anything, even the ground. What can I do? I basically just want the residents not to float above the ground and follow the slopes of the land like regular walking.
Below is the whole code if its needed to help solve my problem.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Resident : MonoBehaviour
{
private Vector3 location;
private Quaternion rotation;
private int speed;
private Vector3 moveDirection = Vector3.zero;
private bool canRotate = true;
Vector3 moveVector;
CharacterController controller;
// Start is called before the first frame update
void Start()
{
transform.rotation *= Quaternion.Euler(-90, 0, 0);
controller = GetComponent<CharacterController>();
speed = 5;
SetRandomPos();
StartCoroutine(ExampleCoroutine());
}
void Update()
{
int gravity = 20;
moveDirection = Vector3.zero;
//Check if cjharacter is grounded
moveDirection.y -= gravity * Time.deltaTime;
// Move the controller
controller.Move(moveDirection * Time.deltaTime);
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, location, step);
if (canRotate)
{
transform.LookAt(location);
transform.rotation *= Quaternion.Euler(-90, 90, 0);
canRotate = false;
}
if (transform.position == location)
{
StartCoroutine(ExampleCoroutine());
}
}
void SetRandomPos()
{
location = new Vector3(Random.Range(transform.position.x - 10f, transform.position.x + 10f), transform.position.y, Random.Range(transform.position.z - 10f, transform.position.z + 10f));
canRotate = true;
}
IEnumerator ExampleCoroutine()
{
//yield on a new YieldInstruction that waits for 5 seconds.
yield return new WaitForSeconds(2);
//After we have waited 5 seconds print the time again.
if (transform.position == location)
{
SetRandomPos();
}
}
}
I am not exactly clear what you intend to do, but saw a few issues with the code and tried to fix them. The snippet is untested, I just added what I believe to be the correction that should fix your issues.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
private Vector3 location;
private Coroutine changeMovement = null;
private float speed;
private Vector3 playerVelocity = Vector3.zero;
CharacterController controller;
// Start is called before the first frame update
void Start()
{
controller = GetComponent<CharacterController>();
speed = 5;
SetRandomPos();
}
void Update()
{
bool groundedPlayer = controller.isGrounded;
if (groundedPlayer && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
Vector3 move = (transform.position - location).normalized;
controller.Move(move * Time.deltaTime * speed);
if (move != Vector3.zero)
{
gameObject.transform.forward = move;
}
// check if we are close to our goal, then change the goal
if (changeMovement == null && Vector3.Distance(transform.position,location) < 0.1f)
{
changeMovement = StartCoroutine(ExampleCoroutine());
}
playerVelocity.y += gravityValue * Time.deltaTime;
controller.Move(playerVelocity * Time.deltaTime);
}
void SetRandomPos()
{
location = new Vector3(Random.Range(transform.position.x - 10f, transform.position.x + 10f), transform.position.y, Random.Range(transform.position.z - 10f, transform.position.z + 10f));
}
IEnumerator ExampleCoroutine()
{
//yield on a new YieldInstruction that waits for 5 seconds.
yield return new WaitForSeconds(2);
SetRandomPos();
changeMovement = null;
}
Edit: I changed the code and used the CharacterController.Move as a base.

C#: y axis velocity increasing over time

So....i worked on some code that makes your rocket rotate when you press space
and added a force to the right and it seems like as you go more the velocity increases, why is that?
Sorry for my exprimation, I'm a beginner in unity and programming so..dodon't judge me
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerMovement: MonoBehaviour
{
private float gravity;
public float moveSpeed = 20f;
private Rigidbody2D rb;
private Vector2 startPos;
public Vector2 velocity;
public static PlayerMovement Instance
{
get;
set;
}
// Start is called before the first frame update
private void Start()
{
Instance = this;
startPos = transform.position;
rb = GetComponent < Rigidbody2D > ();
gravity = rb.gravityScale;
}
// Update is called once per frame
private void Update()
{
Vector2 vel = rb.velocity;
float ang = Mathf.Atan2(vel.y, x: 30) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(x: 0, y: 0, z: ang - 90));
rb.AddForce( - velocity * Time.deltaTime, ForceMode2D.Impulse);
rb.AddForce(Vector2.right * 500 * Time.deltaTime);
if (Input.GetKey(KeyCode.Space)) {
rb.AddForce(Vector2.up * 3000 * gravity * Time.deltaTime);
}
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Obstacle")
{
Die();
}
}
void Die()
{
SceneManager.LoadScene(0);
}
}
RigidBody.AddForce is the reason, whenever you using it, it add a force to your game object, and you do this on each frame.

Unity2D: How to get object to move forward

I am trying to run a simple script to get an object to move forward within unity.
My code is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveToHold : MonoBehaviour {
private float traveledDistance;
public int moveSpeed = 10;
private bool isMoving;
public GameObject Aircraft;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (isMoving == true)
{
//Aircraft.transform.position += transform.forward * Time.deltaTime * moveSpeed;
Aircraft.transform.position += transform.forward * moveSpeed * Time.deltaTime;
}
}
public void move ()
{
isMoving = true;
Debug.Log(isMoving);
}
}
As far as I can see, the transform.position should work.
Any ideas?
Try changing :
Aircraft.transform.position += transform.forward * moveSpeed * Time.deltaTime;
to :
Aircraft.transform.position += transform.right * moveSpeed * Time.deltaTime;
Sometimes with unity2D the forward axis is the Z so you're pushing it inside the Z axis which you won't see. Right will move it on the x axis.
I think you need to apply your position to the RigidBody object rather than the aircraft. If I'm guessing right, that should be your aircraft's parent. Try:
Aircraft.parent.transform.position += transform.forward * moveSpeed * Time.deltaTime;

my collision 2d doesn't work in C# on Unity

I'm learning C# while programming my game, I'm stuck doing the movement. I want my character to move continuously by pressing 'D' or 'A' once. Then, after colliding with an invisible wall while going to the right, go backwards until it hits another invisible wall and stop.
I managed to make my GameObject move, but when it collides with the wall, nothing happens. Both objects have a rigidbody2D, the same z-coordinates, and correct tags.
public class SquadMovement : MonoBehaviour {
float speed;
bool collisionRightWall = false;
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.D)) {
CancelInvoke ();
InvokeRepeating ("RightMovement", Time.deltaTime, Time.deltaTime);
}
if (Input.GetKeyDown (KeyCode.A)) {
CancelInvoke ();
InvokeRepeating ("LeftMovement", Time.deltaTime, Time.deltaTime);
}
}
void RightMovement () {
speed = 10f;
transform.Translate (speed * Time.deltaTime, 0, 0);
}
void LeftMovement () {
speed = -7f;
transform.Translate (speed * Time.deltaTime, 0, 0);
}
void OnCollisionWallR (Collider2D colR) {
if (colR.gameObject.tag == "invisibleWallRight") {
collisionRightWall = true;
Debug.Log (collisionRightWall);
}
}
}
I'm using invisible walls because I don't know how to use x-coordinates, There HAS to be a more efficient way but I want to know first why this don't work. I would be glad if someone could teach me that too.
using UnityEngine;
using System.Collections;
public class SquadMovement : MonoBehaviour {
float constantspeed = 3;
float speed;
//Key inputs
void Update () {
transform.Translate (constantspeed * Time.deltaTime, 0, 0);
if (Input.GetKeyDown (KeyCode.D)) {
StopAllCoroutines ();
StartCoroutine (RightMovement(0f));
}
if (Input.GetKeyDown (KeyCode.A)) {
StopAllCoroutines ();
StartCoroutine (LeftMovement(0f));
}
}
//Movement itself (Right, Left)
IEnumerator RightMovement (float Rloop) {
while (transform.position.x < Time.time * constantspeed + 6) {
speed = 10f;
transform.Translate (speed * Time.deltaTime, 0, 0);
yield return new WaitForSeconds (Rloop);
}
if (transform.position.x > Time.time * constantspeed + 5.9) {
StopAllCoroutines ();
StartCoroutine (LeftMovement (0f));
}
}
IEnumerator LeftMovement (float Lloop) {
while (transform.position.x > Time.time * constantspeed -8) {
speed = -7f;
transform.Translate (speed * Time.deltaTime, 0, 0);
yield return new WaitForSeconds (Lloop);
}
}
}

Categories