Reputation: 64236
I am creating a horizontal side-scrolling shooter which I plan to release on mobile devices. How can I set up the ship so that:
The ship must not be able to pass through obstacles.
I created a custom character controller which simply adjust position based on velocity. I cannot figure out how to detect collision and avoid moving through obstacles. There must be an easier way to achieve this simple requirement.
Note: To clarify, the camera follows the ship, it does not automatically scroll. The player can stop the ship by releasing input button.
Upvotes: 1
Views: 5201
Reputation: 64236
I was storing my own velocity
vector which I was then applying using transform.Translate
. This obviously was ignoring any collision detection and would have required a custom collision detection implementation.
Instead I found that the Rigidbody
component contains its own velocity
variable. That velocity value can be easily altered and the object will automatically translate and collide with obstacles. Here is an example:
using UnityEngine;
using System.Collections;
public class CharacterController : MonoBehaviour {
public Vector2 maximumSpeed = new Vector2(1.0f, 1.0f);
void Start() {
}
void Update() {
Rigidbody rigidbody = GetComponent<Rigidbody>();
Vector2 velocity = new Vector2();
velocity.x = Input.GetAxis("Horizontal") * maximumSpeed.x;
velocity.y = Input.GetAxis("Vertical") * maximumSpeed.y;
rigidbody.velocity = velocity;
}
}
This appears to work quite well. Comments would be appreciated :-)
Upvotes: 0