Simple ball controler using accelerometer script written in C#.

using UnityEngine;
using System.Collections;

// © 2017 TheFlyingKeyboard and released under MIT License
// 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 *

This website stores some user agent data. These data are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to opt-out of any future tracking, a cookie will be set up in your browser to remember this choice for one year. I Agree, Deny
504

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close