- Home /
How to Add Gravity to Dynamic Object Created at Runtime
Hi All
How do you add gravity to the following Dynamic Object created at runtime so the Player moves along the terrain, hills, etc in the scene?
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
public float forwardSpeed = 10;
public float backwardSpeed = 8;
public float rotationSpeed = 40;
// Dirty flag for checking if movement was made or not
public bool MovementDirty {get; set;}
void Start() {
MovementDirty = false;
}
void Update () {
// Forward/backward makes player model move
float translation = Input.GetAxis("Vertical");
if (translation != 0) {
this.transform.Translate(0, 0, translation * Time.deltaTime * forwardSpeed);
MovementDirty = true;
}
// Left/right makes player model rotate around own axis
float rotation = Input.GetAxis("Horizontal");
if (rotation != 0) {
this.transform.Rotate(Vector3.up, rotation * Time.deltaTime * rotationSpeed);
MovementDirty = true;
}
}
}
Many thanks in advance
Comment
Answer by DaveA · Jan 10, 2013 at 11:10 PM
Not at design-time in the Inspector?
void Start() {
MovementDirty = false;
AddComponent<CharacterController>();
}
Thanks Dave - what I meant at runtime is the Player (for example a cube) is created at runtime (spawn - multiplayer) and the above script is fired
How would I add gravity that when the above script is fired and movement takes place with the Player (ex. cube), the cube remains bumping along the ground and not floating in Y space?
$$anonymous$$any thanks
Your answer
