Simple ball controler using accelerometer script written in C#.

using UnityEngine;
using System.Collections;

// © 2017 TheFlyingKeyboard
// theflyingkeyboard.net

public class BallController : MonoBehaviour {
    public float speed;
    public float jumpForce;

    private bool isGrounded;

    private Rigidbody rigidbody;

    private float startX;
    private float startY;

    void Start()
    {
        rigidbody = GetComponent<Rigidbody>();
        isGrounded = true;

        startX = Input.acceleration.x;
        startY = Input.acceleration.y;
    }

    void FixedUpdate()
    {
    //Building a force vector 
     Vector3 movement = new Vector3(-(startX - Input.acceleration.x), 0.0f, -(startY - Input.acceleration.y));
    // Adding force to rigidbody
    rigidbody.AddForce(movement * speed * Time.deltaTime);


        if (Input.GetKeyDown(KeyCode.Mouse0) && isGrounded) //Makes ball jump
        {
            rigidbody.AddForce(Vector3.up * jumpForce);
            isGrounded = false;
        }
    }

    void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.tag == "Ground") //Checks if player is on the ground
        {
            isGrounded = true;
        }
    }

}

 

Unity C# 3D Ball Accelerometer Controls
Tagged on:         

2 thoughts on “Unity C# 3D Ball Accelerometer Controls

  • August 5, 2017 at 12:48 am
    Permalink

    You aϲtually make it seem so easү with youг presentatіon but I find tһis matter to be actually something which I think I would never understand.
    It seems too complicated and very broad for me.
    I’m looking forward for your next post, I’ⅼl try to
    get the hang of it!

    Reply
    • August 9, 2017 at 11:53 am
      Permalink

      I’m glad to hear that 🙂

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *