Detect collisions between 2 objects - unity3d

I'm trying to do a little game on mobile using Unity and I've got a problem with the rotation of a maze.
To add context :
When your moving your finger on the screen, the maze is rotating on himself. There is a ball in it and you need to make it go on a cell to win the level.
When the maze is rotating too fast, the ball falls down and go through the ground and I don't know how to fix it.
I tried to play with the gravity, colliders...
This is the same when the ball is jumping (when the maze is going up and down quickly).
For the moment I just reset the ball position when you're falling.
{
ball.transform.position = new Vector3(0, 2, 0);
maze.transform.position = Vector3.zero;
maze.transform.rotation = Quaternion.identity;
}
Do you guys have some ideas ? Thanks

I had a similar problem in a tilt maze mini-game I worked on. Ideally implementing jkimishere's solution will work but I assume the maze is moving too fast for the collisions to register properly. You'll need to smooth the maze's rotation with a Lerp. In our case we had pressure plates with a tilt value, so it doesn't directly translate to your mobile use but perhaps give you a nudge in the right direction. We used:
public GameObject maze;
private float _lerpTime;
private bool _isRotating;
private Quaternion _startingRot, _desiredRot;
private void Awake()
{
_startingRot = maze.transform.localRotation;
}
private void Update()
{
//Don't want to move the maze if we don't ask for it
if(!_isRotating)
return;
//Lerp the maze's rotation
_lerpTime = Mathf.Clamp(_lerpTime + Time.deltaTime * 0.5f, 0f, 1f);
maze.transform.localRotation = Quaternion.Lerp(_startingRot, _desiredRot, _lerpTime);
//Once the maze gets where it needs to be, stop moving it
if(affectedObject.transform.localRotation.Equals(_desiredRot)
_isRotating = false;
}
private void ActivateTilt()
{
//Set the new starting point of the rotation.
_startingRot = maze.transform.localRotation;
//However you want to calculate the desired rotation here
//Reset our lerp and start rotating again
_lerpTime = 0f;
_isRotating = true;
}
This will ease the rotation of your maze over time. So that the ball can adapt to the new collider positions.

In the rigidbody(for the ball), make the collision detection to continuous, and in the rigidbody for the maze(if you have one) set the collision detection to continuous dynamic. Hope this helps!

I think that is unavoidable if you allow the player to move the platform freely. I suggest you restrain the speed at wich the player can tilt the platform. This way, the ball will have more frames to adapt to the new slope

Related

Unity2D - natural physics for two colliding spheres/balls

In my 2D Unity game, balls can bounce off each other. My goal is to have them bounce off each other as you would expect physically in the real world.
The only difference is that the speed of the balls decreases, but they can never come to a stop.
I have different approaches to map the physical behavior. But none of them leads to a good result.
(1)
private void OnCollisionEnter2D(Collision2D collision) {
var point = collision.GetContact(0);
var curDire = transform.TransformDirection(Vector2.up);
var newDir = Vector2.Reflect(curDire, point.normal);
transform.rotation = Quaternion.FromToRotation(Vector2.up, newDir);
speed *= 0.75f;
}
I don't know how describe exactly: It can happen that the balls push past each other. They collide, but do not bounce off each other, but maintain their direction.
Another approach I have read about is to add an AddForce to the velocity of Rigidbody2D.
Then the following code should do the physics.
private void Start()
{
rb = GetComponent<Rigidbody2D>();
_velocity = new Vector3(1f, 1f, 0f);
_rb.AddForce(_velocity, ForceMode2D.Force);
}
private void OnCollisionEnter2D(Collision2D collision) {
var inDirection = GetComponent<Rigidbody2D>().velocity;
var inNormal = collision.contacts[0].point;
var newVelocity = Vector2.Reflect(inDirection, inNormal);
rb.velocity = newVelocity;
}
The results are really random. I think I use a wrong AddForce or the velocity-Vector is strange. I fall here the deeper mathematical understanding to fully comprehend this solution.
(3) Then I read about Physic Material 2D. This sounds best. I created one (Asset -> Create -> 2D -> Physic Material 2D). Set bounciness to 1 the friction to 0.1. I select my Ball-prefab and add the physic material to my collider. I added it to the Rigidbody2D, too. But this asset has no effect. (My balls have no gravity. I don't know if this is important.)
I imagine Unity has a super simple solution for this problem. But I just can't find it. Does anyone have any ideas or approaches for me? I actually just want shot balls to bounce off each other. This should look as much as possible like it would look in real life.
Update Question
I move the ball like that
private Vector3 _inDirection;
private void Start()
{
_inDirection = Vector3.right * (speed * Time.deltaTime * (_didCollide ? -1 : 1));
}
private void FixedUpdate()
{
transform.Translate(_inDirection);
}

Unity / Mirror - Is there a way to keep my camera independent from the player object's prefab after start?

I'm currently trying to create a multiplayer game using mirror!
So far I've been successful in creating a lobby and set up a simple character model with a player locomotion script I've taken and learnt inside out from Sebastian Graves on YouTube (you may know him as the dark souls III tutorial guy)
This player locomotion script uses unity's package 'Input System' and is also dependent on using the camera's .forward and .right directions to determine where the player moves and rotates instead of using forces on the rigidbody. This means you actually need the camera free in the scene and unparented from the player.
Here is my HandleRotation() function for rotating my character (not the camera's rotation function):
private void HandleRotation()
{
// target direction is the way we want our player to rotate and move // setting it to 0
Vector3 targetDirection = Vector3.zero;
targetDirection = cameraManager.cameraTransform.forward * inputHandler.verticalInput;
targetDirection += cameraManager.cameraTransform.right * inputHandler.horizontalInput;
targetDirection.Normalize();
targetDirection.y = 0;
if (targetDirection == Vector3.zero)
{
// keep our rotation facing the way we stopped
targetDirection = transform.forward;
}
// Quaternion's are used to calculate rotations
// Look towards our target direction
Quaternion targetRotation = Quaternion.LookRotation(targetDirection);
// Slerp = rotation between current rotation and target rotation by the speed you want to rotate * constant time regardless of framerates
Quaternion playerRotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
transform.rotation = playerRotation;
}
It's also worth mentioning I'm not using cinemachine however I'm open to learning cinemachine as it may be beneficial in the future.
However, from what I've learnt and managed to find about mirror is that you have to parent the Main Camera under your player object's prefab so that when multiple people load in, multiple camera's are created. This has to happen on a Start() function or similar like OnStartLocalPlayer().
public override void OnStartLocalPlayer()
{
if (mainCam != null)
{
// configure and make camera a child of player
mainCam.orthographic = false;
mainCam.transform.SetParent(cameraPivotTransform);
mainCam.transform.localPosition = new Vector3(0f, 0f, -3f);
mainCam.transform.localEulerAngles = new Vector3(0f, 0f, 0f);
cameraTransform = GetComponentInChildren<Camera>().transform;
defaultPosition = cameraTransform.localPosition.z;
}
}
But of course, that means that the camera is no longer independent to the player and so what ends up happening is the camera rotates when the player rotates.
E.g. if I'm in game and looking to the right of my player model and then press 'w' to walk in the direction the camera is facing, my camera will spin with the player keeping the same rotation while my player spins in order to try and walk in the direction the camera is facing.
What my question here would be: Is there a way to create a system using mirror that doesn't require the camera to be parented to the player object prefab on start, and INSTEAD works by keeping it independent in the scene?
(I understand that using forces on a rigidbody is another method of creating a player locomotion script however I would like to avoid that if possible)
If anybody can help that would be greatly appreciated, Thank You! =]
With the constraint of your camera being attached to the player you will have to adapt the camera logic. What you can do is instantiate a proxy transform for the camera and copy that transforms properties to your camera, globally, every frame. The parent constraint component might do this for you. Then do all your transformations on that proxy.
Camera script with instantiation:
Transform proxy;
void Start(){
proxy = (new GameObject()).transform;
}
void Update(){
//transformations on proxy
transform.position = proxy.position;
transform.rotation = proxy.rotation;
}

Raycast2D hits only one side of Collider

I want to make sure that various objects moving at high speed cannot pass through walls or other objects. My thought process was to check via Raycast if a collision has occurred between two moments of movement.
So the script should remember the previous position and check via Raycast for collisions between previous and current position.
If a collision has occurred, the object should be positioned at the meeting point and moved slightly in the direction of the previous position.
My problem is that works outside the map not inside. If I go from inside to outside, I can go through the walls. From outside to inside not.
Obviously I have misunderstood something regarding the application with raycasts.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObsticalControll : MonoBehaviour
{
private Vector3 positionBefore;
public LayerMask collisionLayer = 9;
private Vector3 lastHit = new Vector3(0, 0, -20);
// Start is called before the first frame update
void Start()
{
positionBefore = transform.position;
}
private void OnDrawGizmos()
{
Gizmos.DrawCube(lastHit, new Vector3(.2f,.2f,.2f));
}
// Update is called once per frame
void Update()
{
Vector3 curruentMovement = transform.position;
Vector2 dVector = (Vector2)transform.position - (Vector2)positionBefore;
float distance = Vector2.Distance((Vector2)positionBefore, (Vector2)curruentMovement);
RaycastHit2D[] hits = Physics2D.RaycastAll((Vector2)positionBefore, dVector, distance, collisionLayer);
if(hits.Length > 0)
{
Debug.Log(hits.Length);
for (int i = hits.Length -1 ; i >= 0 ; i--)
{
RaycastHit2D hit = hits[i];
if (hit.collider != null)
{
Debug.Log("hit");
lastHit.x = hit.point.x;
lastHit.y = hit.point.y;
Vector3 resetPos = new Vector3(hit.point.x, hit.point.y, transform.position.z) + positionBefore.normalized * 0.1f;
transform.position = new Vector3(resetPos.x, resetPos.y, transform.position.z);
}
}
}
positionBefore = transform.position;
}
}
Theres a better way to deal with this that unity has built in.
Assuming the object thats moving at a high speed has a RigidBody(2d in your case) you can set its Collision Detection to Continuous instead of Discrete.
This will help collisions with high speed collision, assuming that its moving at high speed and the wall is not moving.
If for some reason you cannot apply this to your scenario, Ill try to help with the raycast solution.
However, I am still wondering about the collision behavior of my raycast script. That would be surely interesting, if you want to calculate shots or similar via raycast
Alright, so your initial idea was to check if a collision had occurred, By checking its current position and its previous position. And checking if anything is between them, that means a collision has occurred. And you would teleport it back to where it was suppose to have hit.
A better way todo this would be to check where the GameObject would be in the next frame, by raycasting ahead of it, by the distance that it will travel. If it does hit something that means that within the next frame, it would have collided with it. So you could stop it at the collision hit point, and get what it has hit. (This means you wouldn't have to teleport it back, So there wouldn't be a frame where it goes through then goes back)
Almost the same idea but slightly less complicated.
Problem would be that if another object were to appear between them within the next frame aswell, it could not account for that. Which is where the rigidbody.movePosition shines, And with OnCollisionEnter you can detect when and what it collided with correctly. Aswell as without the need to teleport it back

On Finger Touch and Drag Rotate 3D Ball - Unity 3D

My 3d ball was moving continuously in the forward direction so I want to give X-rotation for this plus game player was dragging ball horizontally on the screen so for this horizontal movement, I want to give Z-rotation.
To achieve my desire, the result I have made ball parent and child game objects, where parent game object only contains collider and rigidbody and this will do the actual physical movement.
Another side, child game object only contains mesh renderer, this will do desire rotation.
Following image gives you more idea about my structure:
Ball Parent:
Ball Child:
For giving rotation to ball mesh as like parent physics ball, I have written this code:
public class BallMeshRolling : MonoBehaviour
{
private Vector3 ballLastPosition;
void Start ()
{
ballLastPosition = transform.parent.position;
}
void Update ()
{
//implementation-1
//float speed = Vector3.Distance (transform.parent.position, ballLastPosition) * 30f;
//transform.RotateAround (transform.position, Vector3.right, speed);
//implementation-2
//Vector3 differenceInPosition = (transform.parent.position - ballLastPosition).normalized;
//transform.Rotate (differenceInPosition * 10f);
//implementation-3
Vector3 differenceInPosition = (transform.parent.position - ballLastPosition).normalized * 50f;
Quaternion rotation = Quaternion.LookRotation(differenceInPosition);
transform.rotation = rotation;
ballLastPosition = transform.parent.position;
}
}
But none of the above ways working properly, so I expect some other better suggestions from your side.
EDIT: Overall I am trying to achieve something like this:
Catch up - Ketchapp - Highscore 1274
There is a tutorial series from Unity about rolling and moving a 3d ball that can help you to figure out the basics for your problem. Wish it could help.
Roll-a-ball tutorial in Unity Tutorials

Unity Navmeshagent won't face the target object when reaches stopping distance

I'm trying to get the NPC to look at the main character when I'm talking to him. I need to make sure it looks natural and that he is facing me. I know I can do Transform.LookAt() but that is too instant and unnatural.
How do I rotate the navmeshagent to face my character when its stopped moving?
Try this out to control the body orientation - the slerp is adjustable to your desired rotation speed (https://docs.unity3d.com/ScriptReference/Quaternion.Slerp.html):
private void FaceTarget(Vector3 destination)
{
Vector3 lookPos = destination - transform.position;
lookPos.y = 0;
Quaternion rotation = Quaternion.LookRotation(lookPos);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, [fill in desired rotation speed]);
}
if(agent.remainingDistance < agent.stoppingDistance)
{
agent.updateRotation = false;
//insert your rotation code here
}
else {
agent.updateRotation = true;
}
This will rotate your agent when it's distance below the stoppingDistance variable. However it will look inhuman, so if you're going for a humanoid ai I'd recommend looking at the unity Mecanim demo (particularly the locomotion scene) as it has code and animations that will properly animate the agent.
Maybe try this Head Look Controller. It's very smooth and blends with animations!
Put the char in a game object and copy the navmesh from the char to the parent, uncheck enable in char. move any scripts up too.
Just spent 5 hours to find this.