Question by
Nobody1 · May 30, 2016 at 02:43 PM ·
space shootermathf.clampboundary
Space Shooter tutorial - Mathf.clamping boundaries
I'm trying to follow the "Space shooter tutorial" #5. The mathf.clamp code used to create boundaries does not seem to function properly. My ship encounters resistance at each boundary, but if I hold the movement key down, the ship slowly works its way through the boundary and offscreen. Can anyone explain what I'm doing wrong?
Here's what my code looks like
using UnityEngine;
using System.Collections;
[System.Serializable]
public class Boundary
{
public float xMin, xMax, zMin, zMax;
}
public class PlayerController : MonoBehaviour {
public float speed;
public float tilt;
public Boundary boundary;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement * speed);
rb.position = new Vector3
(
Mathf.Clamp (rb.position.x, boundary.xMin, boundary.xMax),
0.0f,
Mathf.Clamp (rb.position.z, boundary.zMin, boundary.zMax)
);
rb.rotation = Quaternion.Euler(0.0f, 0.0f, rb.velocity.x * -tilt);
}
}
Comment
Hello, I have the exact same problem. Did you manage to solve it ?
Answer by UniKam · Jun 13, 2017 at 12:37 PM
Change rb.AddForce(movement * speed);
to rb.velocity = movement * speed;
Your answer
![](https://koobas.hobune.stream/wayback/20220612081854im_/https://answers.unity.com/themes/thub/images/avi.jpg)