Hi, im new to unity. I know how to make a script to make a gameobject move forward, turn, shoot, etc using the character controller thing. im making a game where a ball controlled by you collects stars or something. how do i make it so that the ball rolls forward in a realistic way?
thanks.
AddForce() or AddConstantForce() should put you on the right track.
Cool! Something I can actually answer (sort of). Iāve found that using the physics stuff is super easy:
rigidbody.AddForce (moveDirectionAsVector3)
Iām not sure if torque would be āmore realisticā since I donāt know if torque applied to a sphere sitting on a āfloorā would actually calculate friction to cause the movement.
Hereās a starter script where I roll a ball forward with W and backwards with S:
using UnityEngine;
using System.Collections;
public class SphereController : MonoBehaviour {
public Transform target;
public int speed = 5;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void FixedUpdate() {
if ( Input.GetKey(KeyCode.W) ) {
target.rigidbody.AddForce( Vector3.forward * speed );
}
if ( Input.GetKey(KeyCode.S) ) {
target.rigidbody.AddForce( Vector3.back * speed );
}
}
}
And the corresponding YouTube video: http://www.youtube.com/watch?v=XYG9iPPxX8M
Enjoy.
thanks for the fast replys, ill try it out.
just a question: is the code you gave me javascript? or is it c# or boo?
im getting alot of errors D:
Itās C#. What errors are you getting? Clearly, it runs fine for me.
Before running it, in the Unity inspector youāll need to drag and drop your sphere onto the target variable. The sphere must have a rigid body attached. Also, youāll have to attach the script to a game object.
ok thanks. i was putting the code in a javascript file.
thanks! it works great!
Glad to hear it.