Unity 3D realistic accelerometer control - unity3d

How do we achieve a control similar to this game?
https://play.google.com/store/apps/details?id=com.fridgecat.android.atiltlite&hl=en

You can do this with builtin physics:
create a level from some simple scaled cubes (don't forget the ground).
add the ball - a sphere, then and add a RigidBody to it. Set a constraint on the rigidbody - check freeze position y (or it will be able to jump out of the level if you put the device upside down).
add this script anywhere on the scene (for example to the camera):
using UnityEngine;
public class GravityFromAccelerometer : MonoBehaviour {
// gravity constant
public float g=9.8f;
void Update() {
// normalize axis
Physics.gravity=new Vector3(
Input.acceleration.x,
Input.acceleration.z,
Input.acceleration.y
)*g;
}
}
or if you want the physics to just affect this one object, add this script to the object and turn off it's rigidbody's affected by gravity:
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class ForceFromAccelerometer : MonoBehaviour {
// gravity constant
public float g=9.8f;
void FixedUpdate() {
// normalize axis
var gravity = new Vector3 (
Input.acceleration.x,
Input.acceleration.z,
Input.acceleration.y
) * g;
GetComponent<Rigidbody>().AddForce (gravity, ForceMode.Acceleration);
}
}
And now you have working ball physics. To make the ball behave as you'd like, try to play with the rigidbody properties. For example, change the drag to something like 0.1.

Related

Circle Collider Slides on Box Collider when Velocity is slowing down?

I am trying to create a carrom 2D game for learning, i added box colliders 2D all sides and for striker circle collider 2D, and set physics material for all as friction 0 and bounciness 1. and Linear Drag to 1 for stiker.
It all works fine when velocity of impact of striker with sides but velocity is slow its dragging on slides instead of bouncing. where am i doing it wrong?
I am not sure what the problem is but seems like something to do with how the engine is resolving the physics. Try resolving the collision for the individual carrom tokens manually when they hit a surface instead of relying on physics material.
Here is a simple 2D example:
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class ReflectingObject : MonoBehaviour {
[Range(0f, 1f)]
public float bounciness = 1;
private Rigidbody2D m_Rb;
void Awake() {
m_Rb = GetComponent<Rigidbody2D>();
}
void OnCollisionEnter2D(Collision2D col) {
if(col.contactCount > 0) {
// Get the collision contact point
ContactPoint2D point = col.contacts[0];
// Get the current speed of this object
float speed = m_Rb.velocity.magnitude;
// Get the direction where this object is heading to
Vector2 oldDirection = (Vector2)m_Rb.velocity.normalized;
// Get the reflected direction
Vector2 newDirection = Vector2.Reflect(oldDirection, point.normal).normalized;
// Calculate new velocity based on bounciness
Vector2 newVelocity = newDirection * speed * bounciness;
// Assign the velocity
m_Rb.velocity = newVelocity;
}
}
}
Something like this.
Assign this Component to the objects which you want to reflect on collision.

Issues with objects passing through each other in Unity

I was creating a simulation that involved a rotating bucket drum that is supposed to go through rough soil. To simulate this, I made a project in Unity and imported that CAD design of the drum and added in a bunch of spheres for the dirt. Then, I added a mesh collider to the drum, sphere colliders to the dirt, and rigidbodies to everything. I also turned on the continuous dynamic collision detection on both the dirt and the drum, and made sure to turn of isTrigger and isKinematic in both. But whenever I run the sim, the same issue pops up: the spheres just go directly through the drum and nothing I can do will fix it. I've tried looking at other threads but all of those solutions don't work. Can I get some help? Thanks.
Image of the drum before colliding with the spheres
Image of the drum in the middle of the spheres with nothing disturbed
Image of the components on the rotating drum
Image of the components on the spheres (All of them have the same setup)
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotateScript : MonoBehaviour
{
public float thrust = 0.1f;
public float torque = 0.5f;
public Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.AddForce(0, 0, -thrust, ForceMode.Impulse);
}
private void FixedUpdate()
{
float turn = Input.GetAxis("Horizontal");
rb.AddTorque(transform.up * torque * turn);
if(Input.GetKeyDown(KeyCode.W))
{
rb.AddForce(0, 0, (thrust * 2), ForceMode.Impulse);
}
if(Input.GetKeyDown(KeyCode.S))
{
rb.AddForce(0, 0, (-thrust * 2), ForceMode.Impulse);
}
}
}

Camera follow player around planet

I have a planet and a player moving on it using gravity. I would like to have a camera to follow the player around it. Using the Parent Constraint component works perfectly, but I want to delay the rotation follow, so I have to use a script. I just cannot figure out how to make it follow it around the globe. I either have a camera that completely freaks out, or a camera that sort of follows the player but doesn't move over the planet and always stays in front of it. And often the position following works, but as soon as I add something that changes rotation it only does that. I've tried many different scripts but nothing works. I'm grateful for any help.
EDIT
I'm sorry for not adding an example. At the moment I've tried this script attached to the camera:
public class CameraFollow : MonoBehaviour
{
public GameObject player;
private Vector3 offset;
void Start()
{
offset = transform.position - player.transform.position;
}
void LateUpdate()
{
transform.rotation = Quaternion.Slerp(transform.rotation, player.transform.rotation, 50f * Time.deltaTime);
transform.position = player.transform.position + offset;
}
The camera does mimic the rotation of the player, but the position isn't being follow correctly anymore. It seems mostly stuck in place, moving only very slightly.
In order to have a camera following a GameObject, you need to go to the camera you want following the GameObject, select Add component, write FollowPlayer, press New script, and then press select and add. Edit the script so it contains the following:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowPlayer : MonoBehaviour
{
public Transform player;
public Vector3 offset;
// Update is called once per frame
void Update()
{
transform.position = player.position + offset;
}
}
Then, you will need to drag and drop the GameObject you want the camera to follow, in the "Player" box.
Define the offset of the camera from the GameObject, and your'e good to go.

Smooth Camera Follow with Voxel Based Sphere

I am very new to Unity and just got done yesterday following the Roller Ball example on the learn page here at Unity3d.
To practice what I have learned I wanted to try and recreate something similar using my own art and making the game different. I have been playing around with Voxel Art and I am using MagicaVoxel to create my assests. I created the walls, the ground etc.. and all is well.
Then came the player object, the sphere. I created one as close to a sphere as possible with magicaVoxel and it rolls fine. However, when using a script to have the camera follow the object it runs into issues.
If I don't constrain the Y axis then I will get bouncing and as far as the x and z axis I get kind of a Flat Tire effect. Basically the camera doesn't follow smoothly it bounces around, stop go etc...
I have tried making the collider larger then the sphere and even using the position of the collider vs the object itself. I have also tried putting the code in Update / FixedUpdate / LateUpdate. What is the proper way to fix or address something like this? Here is my scripts below:
Camera Controller:
public class CamController : MonoBehaviour {
public GameObject player;
private Vector3 offset;
void Start ()
{
// Get the distance between the player ball and camera.
offset = this.transform.position - player.transform.position;
}
void LateUpdate ()
{
this.transform.position = player.transform.position + offset;
}
}
Player Controller:
public class PlayerController : MonoBehaviour {
public float _speed;
void FixedUpdate()
{
// Get input from keyboard.
float _hoz = Input.GetAxis("Horizontal");
float _ver = Input.GetAxis("Vertical");
// Create a vector3 based on input from keyboard.
Vector3 _move = new Vector3(_hoz, 0.0f, _ver);
// Apply force to the voxel ball
this.GetComponent<Rigidbody>().AddForce(_move * _speed);
}
}
Thanks for any help in advance.
You can use the SmoothFollow Script of Unity it self for getting smooth follow of camera.
Here are the steps how you can get the script:
1) Assets->Import Package->Scripts.
2) At the dialog that appears select all the scripts, or just the smooth follow one and hit Import button.
3) Now this script is in your project, and you can attach it to the camera.
Hope this will help you...
Best,
Hardik.

How to modify the car controllers to do it more Arcade and less realistic in Unity 5 3D

I'm using the Unity 5 Car Asset coming with the Standard Assets. Controls are very hard. The car flips easily even if you are going at quite slow speed.
I have done some "tricks" I have found on the Internet like increasing the mass of the rigid body to 1500, adding the Stabilizer bars (A.K.A. anti-roll bars) script to the car, and setting the gravity center of the car in a fake perfect center. I have included the last versions of those scripts above.
I don't want to simulate perfect physics. I want a fun car easy to ride. Is it possible with Unity?
Script: gravity center of the car in a fake perfect center
using UnityEngine;
using System.Collections;
public class carflipfix : MonoBehaviour {
// Use this for initialization
void Start () {
GetComponent<Rigidbody>().centerOfMass = new Vector3(0, -1, 0);
}
}
Script: stabilizer bars (A.K.A. anti-roll bars).
using UnityEngine;
using System.Collections;
public class AntiRollBar : MonoBehaviour {
public WheelCollider wheelL;
public WheelCollider wheelR;
public float antiRollVal = 5000f;
// Update is called once per frame
void Update () {
WheelHit hit;
float travelL=1.0f;
float travelR=1.0f;
bool groundedL = wheelL.GetGroundHit(out hit);
if (groundedL){
travelL = (-wheelL.transform.InverseTransformPoint(hit.point).y - wheelL.radius) / wheelL.suspensionDistance;
}
bool groundedR = wheelR.GetGroundHit(out hit);
if (groundedR){
travelR = (-wheelR.transform.InverseTransformPoint(hit.point).y - wheelR.radius) / wheelR.suspensionDistance;
}
float antiRollForce = (travelL - travelR) * antiRollVal;
if (groundedL)
GetComponent<Rigidbody>().AddForceAtPosition(wheelL.transform.up * -antiRollForce,
wheelL.transform.position);
if (groundedR)
GetComponent<Rigidbody>().AddForceAtPosition(wheelR.transform.up * antiRollForce,
wheelR.transform.position);
}
}
If we remove the Rigidbody component, we won't be using the Unity physics. Then, we could move the car as we wish getting the input (from the keyboard, gamepad...) to multiply it by the current position of the car. It would be something like:
public class Car: MonoBehaviour
{
public void Update() {
// NOTICE THE FOLLOWING LINE OF CODE IS NOT CORRECT. THE CORRECT WAY SHOULD BE SOMETHING SIMILAR THOUGH:
gameObject.transform.position += input * Time.deltaTime * gameObject.transform.position;
}
}