Adding Gravity to unity character causes character to get pulled backwards

Hello,

I’m a beginner to unity and I’m starting to work through the Unity in Action book published by Manning. Working on an early project creating a 3D shooter. I’ve created a movement script for my character but after adding gravity the character is pulled backward along the Z axis.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(CharacterController))]
[AddComponentMenu("Control Script/FPS input")]

public class FPSInput : MonoBehaviour
{ 

    public float speed = 6.0f;
    public float gravity = -9.8f;

    private CharacterController charController;


    private void Start()
    {
        charController = GetComponent<CharacterController>();
    }
    // Update is called once per frame
    void Update()
    {
        float deltaX = Input.GetAxis("Horizontal") * speed;
        float deltaZ = Input.GetAxis("Vertical") *speed;
        Vector3 movement = new Vector3(deltaX, 0, deltaZ);
        movement = Vector3.ClampMagnitude(movement, speed);
        movement.y = gravity;
        //time.deltaTime to make the speed of movement indepent of the frame rate.
        //transform.Translate(deltaX * Time.deltaTime, 0, deltaZ * Time.deltaTime);
        movement *= Time.deltaTime;
        movement = transform.TransformDirection(movement);
        charController.Move(movement);

    }

}

I believer I’m typing up the code correctly per the book. Wondering if I have some error in the editor or some issue with the code the book is suggesting? I’ve seen this posted from several years ago and appears the poster was using the same book Gravity Seems to be pulling character backwards , I’m not really clear on the answer provided though… Appreciate any help!

Gravity should be in world space, but you’re transforming it into local space on line 32. It should also be an acceleration.

See Unity - Scripting API: CharacterController.Move for a better implementation.