I am trying to make a simple FPS game (more trying to get used to Unity rather than release it) and I’ve encountered 2 problems.
The first one is that whenever I shoot a bullet, the player flys up and forward at a fast pace. Here is the code I am using for the shooting:
var cameraObject : GameObject;
var gun : Transform;
var bullet : Transform;
function Update()
{
if(Input.GetButton("Fire1"))
{
instanceBullet = GameObject.Instantiate(bullet, GameObject.Find("Barrel").transform.position, GameObject.Find("Barrel").transform.rotation);
instanceBullet.rigidbody.AddForce(instanceBullet.transform.forward * 4000);
Destroy(GameObject.instanceBullet,3);
}
}
The second problem I’m having is that the player starts moving forward when the game starts up. I tried setting the velocity of x and y to 0, but that has no effect. This is the movement code:
var walkAcceleration:float = 7;
var walkDeceleration:float = 5;
var walkAccelAirRatio:float = 0.1;
var cameraObject:GameObject;
var maxWalkSpeed:float = 20;
var grounded:boolean = false;
@HideInInspector
var horizontalMovement:Vector2;
var jumpVelocity:float = 200;
@HideInInspector
var maxSlope:float = 35;
function LateUpdate()
{
horizontalMovement = Vector2(rigidbody.velocity.x, rigidbody.velocity.z);
if(horizontalMovement.magnitude > maxWalkSpeed)
{
horizontalMovement = horizontalMovement.normalized;
horizontalMovement *= maxWalkSpeed;
}
rigidbody.velocity.x = horizontalMovement.x;
rigidbody.velocity.z = horizontalMovement.y;
if(Input.GetAxis("Horizontal") == 0 && Input.GetAxis("Vertical") == 0)
{
rigidbody.velocity.x /= walkDeceleration;
rigidbody.velocity.z /= walkDeceleration;
}
transform.rotation = Quaternion.Euler(0, cameraObject.GetComponent(MouseLookScript).currentYRotation, 0);
if(grounded)
rigidbody.AddRelativeForce(Input.GetAxis("Horizontal") * walkAcceleration, 0, Input.GetAxis("Vertical") * walkAcceleration);
else
rigidbody.AddRelativeForce(Input.GetAxis("Horizontal") * walkAcceleration * walkAccelAirRatio, 0, Input.GetAxis("Vertical") * walkAcceleration * walkAccelAirRatio);
if(Input.GetButtonDown("Jump") && grounded)
{
rigidbody.AddForce(0, jumpVelocity, 0);
}
if(Input.GetButtonDown("Sprint"))
{
rigidbody.velocity.x = 0;
rigidbody.velocity.y = 0;
}
}
function OnCollisionStay(collision : Collision)
{
for(var contact:ContactPoint in collision.contacts)
{
if(Vector3.Angle(contact.normal, Vector3.up) < maxSlope)
{
grounded = true;
}
}
}
function OnCollisionExit()
{
grounded = false;
}
any help with these issues would be greatly appreciated.