movement with 3D sprite in unity is not working - c#

I had gotten all the movement working with my ghost, which was a red ball, so i made a sprite (im not sure if that is what you call it) i was able to make one but now the movement is not working. it looks like it is on ice because when it tries to turn it goes diagonal and it speeds up when going straight. I don't know why its doing this because i'm not even putting force into it to move it. (the code):
GameObject.Find("ghosteyes").transform.position = (place + vecmove);
thanks

so what you can do is 3 things. first get your transform,then move it using Translate like this:
private Transform _transform;
private void Start()
{
//this gets the transform that the script is on and sets it to _transform
_transform = this.GetComponent<Transform>();
}
private void Update()
{
float hor = Input.GetAxis("Horizontal");
float vert = Input.GetAxis("Vertical");
_transform.Translate(new Vector2(hor, vert));
}
OR
Add the Input to the position for a more fixed movement.
private Transform _transform;
private void Start()
{
//this gets the transform that the script is on and sets it to _transform
_transform = this.GetComponent<Transform>();
}
private void Update()
{
float hor = Input.GetAxis("Horizontal");
float vert = Input.GetAxis("Vertical");
_transform.position += new Vector3(hor,vert) * Time.deltaTime;
}
OR
create a rigidBody on your player. then put this script on your player. and use rigidbody.MovePosition to move your character. for example:
private Rigidbody2D rb;
private void Start()
{
rb = this.GetComponent<Rigidbody>();
}
private void Update()
{
//This will take in horizontal input like A and D/ arrow left or right.
float hor = Input.GetAxis("Horizontal");
rb.MovePosition(transform.position += new Vector2(hor,0));
}

Related

Enemy is moving in a jittery way and I do not know how to solve this

I am new to Unity and I was working on the enemy's movement of my first video game with C#.
The thing is that whenever the enemy follows the main character, it moves in a very jittery way and I do not know why. I tried a lot of solutions including a different code approach but notthing worked. I tried changing some configurations in its rigid body like collision detection but nothing happend.
This is the code of my enemy:
public class Black : Enemy
{
public float checkRadius;
public float attackRadius;
public bool shouldRotate;
public LayerMask lm;
private Rigidbody2D bd;
private Vector2 movement;
public Vector3 dir;
private bool isInchaseRange;
private bool isInattackRange;
// Start is called before the first frame update
void Start()
{
Debug.Log("Jugador " + player.name);
bd = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
isInchaseRange = Physics2D.OverlapCircle(transform.position, checkRadius, lm);
isInattackRange = Physics2D.OverlapCircle(transform.position, attackRadius, lm);
dir = player.position - transform.position;
dir.Normalize();
movement = dir;
}
void FixedUpdate() {
if (isInchaseRange && !isInattackRange) {
MoveCharacter(movement);
}
if (isInattackRange)
{
bd.velocity = Vector2.zero;
}
}
private void MoveCharacter(Vector2 dir) {
transform.position = Vector2.MoveTowards(transform.position, player.position, speed * Time.deltaTime);
}
}
This is how I move my main character if it helps you
public class PlayerMovement : MonoBehaviour
{
public float speed;
private Rigidbody2D rb;
private Vector2 moveAmount;
public float health;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
Vector2 moveInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
moveAmount = moveInput.normalized * speed;
}
void FixedUpdate()
{
move();
}
void move()
{
rb.MovePosition(rb.position + moveAmount * Time.fixedDeltaTime);
}
public void takeDamage(int damageAmount)
{
health -= damageAmount;
if (health <= 0)
{
Destroy(gameObject);
}
}
}
The character has the same stuff as the enemy: Script, box collider 2d, rigid body
Any ideas on how to solve this?
As you can see by the gif it is not working as it should
https://im2.ezgif.com/tmp/ezgif-2-fbffacda5a27.gif
Thanks
Try making the chase range huge and attack range very small and see if it still moves in a jittery way to make sure it's not jittering because it's going in and out of range very quickly.
Set Rigidbody2D to interpolate from the inspector.
Also for the player, use Time.deltaTime instead of Time.fixedDeltaTime. Although this probably isn't related to your problem, this will give more smooth movement for the player. Time.fixedDeltaTime is just for setting the target you want the unity to stay at, but it will never precisely achieve that frametime. And Time.deltaTime will return the correct value based on whether it's called from Update() or FixedUpdate()
When this is called from inside MonoBehaviour.FixedUpdate, it returns Time.fixedDeltaTime. - Unity Docs

FPS Projectile firing from the wrong place

I'm trying to make a basic FPS game in Unity and I'm having an issue where the projectiles I shoot won't instantiate in the right place. From what I can tell, the projectile instantiates in roughly the same position relative to the player regardless of where I look (that position being a little to the left of the starting angle of the player).
Here's a 20 second video demonstration of what I'm talking about.
https://youtu.be/WLVuqUtMqd0
Even when I'm facing the exact opposite direction of where the projectile usually instantiates it still spawns in the same place, which means the projectile ends up spawning behind the player and hitting the player.
I tried using Debug.DrawRay() to see if maybe the firepoint itself is wrong (which would be shown by the ray starting somewhere other than the gun barrel). However it seems like the starting point of the ray is correct every time.
I'm not sure if this is related to the issue above, but I have noticed that the ray direction is wrong if I'm looking a little below the horizon. It seems like the projectile's direction is correct regardless though.
Ray directions when looking slightly above the horizon vs. lower
Here's my code for intantiating/shooting the projectile. I think the most relevant parts are probably shootProjectile() and instantiateProjectile(). This script is attached to the player character.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooting : MonoBehaviour
{
public Camera cam;
public GameObject projectile;
public Transform firePoint;//firePoint is set to the end of the barrel.
public float projectileSpeed = 40;
//private var ray;
private Vector3 destination;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//var ray = cam.ViewportPointToRay(new Vector3(0.5f,0.5f,0));
//Debug.DrawRay(ray.origin, ray.direction);
if(Input.GetButtonDown("Fire1")) {
//player is shooting
ShootProjectile();
}
}
void ShootProjectile() {
Ray ray1 = cam.ScreenPointToRay(Input.mousePosition);
//Debug.Log(ray.direction);
RaycastHit hit;
if(Physics.Raycast(ray1, out hit))//checking whether the player is going to hit something
{
destination = hit.point;
}
else {
destination = ray1.GetPoint(1000);
}
Debug.DrawRay(firePoint.position, destination, Color.white, 10f);
InstantiateProjectile(firePoint);
}
void InstantiateProjectile(Transform firePoint) {
var projectileObj = Instantiate (projectile, firePoint.position, Quaternion.identity) as GameObject;//projectile is instantiated
projectileObj.GetComponent<Rigidbody>().velocity = (destination - firePoint.position).normalized * projectileSpeed;//projectile is set in motion
}
}
Here's the location of firePoint.
firePoint (i.e. where the projectile should instantiate)
I would appreciate any help on this, as I've been trying to fix it (on and off) for several days, and really have no idea what the problem is.
Edit: Here's my player movement script(s) as well. The first one is PlayerController.cs, and it converts the player's inputs into the appropriate movement vectors and camera rotation. It then calls methods from PlayerMotor.cs, which actually performs the movements.
PlayerController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(PlayerMotor))]
public class PlayerController : MonoBehaviour
{
[SerializeField]
public float speed = 10f;
[SerializeField]
private float lookSens = 3f;
private PlayerMotor motor;
void Start() {
motor = GetComponent<PlayerMotor>();
//Debug.Log("PlayerControllerStart");
Cursor.lockState = CursorLockMode.Locked;
}
void Update() {
//Debug.Log("PlayerControllerUpdate");
//calculate movement velocity as 3D vector.
float xMov = Input.GetAxisRaw("Horizontal");
float zMov = Input.GetAxisRaw("Vertical");
Vector3 movHorizontal = transform.right * xMov;
Vector3 movVertical = transform.forward * zMov;
Vector3 velocity = (movHorizontal + movVertical).normalized * speed;
motor.move(velocity);
//speed*=(float)1.15;
//rotation
float yRot = Input.GetAxisRaw("Mouse X");
Vector3 rotation = new Vector3 (0f, yRot, 0f) * lookSens;
motor.rotate(rotation);
float xRot = Input.GetAxisRaw("Mouse Y");
Vector3 cameraRotation = new Vector3 (xRot, 0f, 0f) * lookSens;
motor.rotateCamera(cameraRotation);
if (Input.GetKeyDown(KeyCode.Space) == true && motor.isGrounded()) {
motor.canJump=true;
}
if (Input.GetKey(KeyCode.W) == true) {
motor.accel=true;
}
else{
motor.accel=false;
}
}
}
PlayerMotor:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerMotor : MonoBehaviour
{
[SerializeField]
private Camera cam;
private Vector3 velocity = Vector3.zero;
private Vector3 rotation = Vector3.zero;
private Vector3 cameraRotation = Vector3.zero;
private Vector3 jumpVector = new Vector3 (0f, 5f, 0f);
private PlayerController pc;
private Rigidbody rb;
public bool canJump;
public bool accel;
public float acceleration;
int jumpCount;
void Start() {
rb = GetComponent<Rigidbody>();
pc = GetComponent<PlayerController>();
canJump=false;
jumpCount=0;
accel=false;
//acceleration = 1.0;
//distToGround = collider.bounds.extents.y;
//Debug.Log("PlayerMotorStart");
}
//sets velocity to a given movement vector.
public void move(Vector3 _velocity) {
velocity = _velocity;
}
public void rotate(Vector3 _rotation) {
rotation = _rotation;
}
public void rotateCamera(Vector3 _cameraRotation) {
cameraRotation = _cameraRotation;
}
public bool isGrounded() {
return Physics.Raycast(transform.position, -Vector3.up, (float)2.5);
}
public void jump() {
rb.AddForce(transform.up * 250f);
//Debug.Log("Jump"+jumpCount);
jumpCount++;
canJump=false;
}
void FixedUpdate() {
performMovement();
performRotation();
if (canJump) {
jump();
}
//Debug.Log("PlayerMotorUpdate");
if(accel&&pc.speed<20f&&isGrounded())
{
//Debug.Log("W Pressed");
pc.speed*=(float)1.005;
}
else if(!accel) {
pc.speed=7f;
}
}
void performMovement() {
if(velocity != Vector3.zero) {
rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
//Debug.Log("Movement");
}
}
void performRotation() {
rb.MoveRotation(rb.rotation * Quaternion.Euler(rotation));
if(cam != null) {
cam.transform.Rotate(-cameraRotation);
}
}
}
Here are some pictures of my projectile prefab as well.
To solve one first confusion: The method Debug.DrawRay takes as paramters
a start position
a ray direction(!)
You are passing in another position which is not what you want.
This might only work "accidentally" as long as you stand on 0,0,0 so maybe it wasn't that notable but the debt ray definitely points into a wrong direction.
Rather do e.g.
Debug.DrawRay(firePoint.position, destination - firePoint.position, Color.white, 10f);
Or instead rather use Debug.DrawLine which rather actually takes
start position
end position
Then you don't need to calculate the direction first
Debug.DrawLine(firePoint.position, destination, Color.white, 10f);
Then I suspect the following is happening: The spawned projectileObj actually is placed correctly but it is the visuals inside that projectile prefab that have a local offset against the parent prefab root.
Since you always spawn the projectile in world rotation Quaternion.identity that offset stays the same no matter where you look.
I guess a simple fix would already be to also apply the same rotation like
var projectileObj = Instantiate (projectile, firePoint.position, firePoint.rotation);

I have followed a tutorial on making controls for a fps game on unity. the controls work but if I leave the controls then I keep moving to the left

enter image description hereI have made controls for my character to move along the X axis. They seem to be working fine but my character keeps moving left and I'm not sure why or what I have missed.I have posted code from the two separate scripts
I have rechecked his code several times.I have checked to see if my arrow keys, numpad keys and WASD are sticking or any other.
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerMotor : MonoBehaviour
{
private Vector3 velocity = Vector3.zero;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
//gets a movement vector
public void Move (Vector3 _velocity)
{
velocity = _velocity;
}
//run every physics iteration
void FixedUpdate()
{
PerformMovement();
}
//perform movement based on velocity variable
void PerformMovement ()
{
if (velocity != Vector3.zero)
{
rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
}
}
}
And the controller:
using UnityEngine;
[RequireComponent(typeof(PlayerMotor))]
public class PlayerController : MonoBehaviour
{
[SerializeField] //makes speed show up in inspector even if set to private
private float speed = 5f;
private PlayerMotor motor;
void Start ()
{
motor = GetComponent<PlayerMotor>();
}
void Update()
{
//Calculate movement velocity as a 3D vector
float _xMov = Input.GetAxisRaw("Horizontal");
float _zMov = Input.GetAxisRaw("Vertical");
Vector3 _movHorizontal = transform.right * _xMov;
Vector3 _movVertical = transform.forward * _zMov;
//final movement vector
Vector3 _velocity = (_movHorizontal + _movVertical).normalized * speed;
//apply movement
motor.Move(_velocity);
}
}
I expect 0 output when not pressing buttons but it seems to make me move to the left at speed of 5
You have a controller connected and reporting a slight movement in one direction. Use Input.GetAxis instead of Input.GetAxisRaw to let Unity handle deadzone detection. This way, nearly neutral inputs will be treated as neutral inputs.
void Update()
{
//Calculate movement velocity as a 3D vector
float _xMov = Input.GetAxis("Horizontal");
float _zMov = Input.GetAxis("Vertical");
Vector3 _movHorizontal = transform.right * _xMov;
Vector3 _movVertical = transform.forward * _zMov;
//final movement vector
Vector3 _velocity = (_movHorizontal + _movVertical).normalized * speed;
//apply movement
motor.Move(_velocity);
}

How do I make my character run around the camera in third person?

I'm working on a third-person run-around game and there's a specific kind of movement I've wanted to achieve but I'm having trouble even imagining how it would work, let alone actually coding it.
Essentially, when holding left or right, I want the player to orbit the camera. Such a camera effect can be seen here. That's exactly what I want to achieve.
Here's my movement and camera code so far. I image I'll need to use the camera's Y rotation to achieve this but my tests haven't worked out. Any input would be appreciated!
Movement:
public int speed = 10;
public int rotationSpeed = 10;
public CharacterController cc;
Vector2 input;
Vector3 moveDir;
Vector3 lookDir;
Vector3 forward;
Transform camTransform;
public Transform model;
void Start () {
cc = GetComponent<CharacterController>();
camTransform = Camera.main.transform;
}
void GetInput() {
input.x = Input.GetAxisRaw("Horizontal");
input.y = Input.GetAxisRaw("Vertical");
}
void CalculateForward()
{
}
void Move()
{
moveDir.x = input.x;
moveDir.z = input.y;
if(moveDir.magnitude > 1)
{
moveDir.Normalize();
}
Vector3 rotatedDir = Camera.main.transform.TransformDirection(moveDir);
rotatedDir = new Vector3(rotatedDir.x, 0, rotatedDir.z);
rotatedDir = rotatedDir.normalized * moveDir.magnitude;
cc.Move(rotatedDir * speed * Time.deltaTime);
}
void ApplyGravity()
{
}
void FaceDir()
{
if (moveDir != Vector3.zero)
{
transform.rotation = Quaternion.Slerp(
transform.rotation,
Quaternion.LookRotation(-moveDir),
Time.deltaTime * rotationSpeed
);
}
}
private void FixedUpdate()
{
GetInput();
//ApplyGravity();
Move();
FaceDir();
ApplyGravity();
}
}
Camera:
[SerializeField]
private float distanceAway;
[SerializeField]
private float distanceUp;
[SerializeField]
private float smooth;
[SerializeField]
private Transform follow;
private Vector3 targetPosition;
private void Start()
{
follow = GameObject.FindWithTag("Player").transform;
}
private void LateUpdate()
{
targetPosition = follow.position + follow.up * distanceUp - follow.forward * distanceAway;
transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * smooth);
transform.LookAt(follow);
}
Movement around a circle is always in a direction tangential to the circle, so with each update you want to:
Set the Y rotation of the player to be looking directly at the Y axis of the camera
rotate the player 90 degrees left or right (depending on the direction you want to go)
move the player forward a distance that will depend on the speed with which you would like them to move
Remember it's impossible to traverse a circle perfectly because there are infinitely many points on a circle but this approach will approximate it well enough.

Projectile Y-axis start position - 2.5D Platform

I have this issue and I can't fix it. I've already tried to search on internet but I found nothing.
The "projectile spawn" is situated next to my character. When I left-click on my mouse, the projectile starts shooting going forward (in the Z-axis at 20 speed, for example) but there is this issue that is making me mad. Sometimes it starts from the right place, sometimes under and under every click.
public Rigidbody projectile;
public float speed = 20;
private Transform spawnPoint;
private int SPAWN_DISTANCE = 1;
void Awake()
{
spawnPoint = transform.Find("SpawnPoint");
}
void Update ()
{
//
if (Input.GetButtonDown("Fire1"))
{
atkSpeed = 0.2f;
Shoot(projectile);
attackTime = atkSpeed;
chargeLevel = 0;
}
//
}
void Shoot(Rigidbody proj){
Rigidbody _projBody = Instantiate(proj, spawnPoint.position + SPAWN_DISTANCE * transform.forward, transform.rotation) as Rigidbody;
_projBody.velocity = transform.TransformDirection(new Vector3(0, 0,speed));
}
Video of what is happening: https://www.youtube.com/watch?v=GLgrfl2zU9w
EDIT: I SOLVED MYSELF YESTERDAY.
Put an Empty GameObject where you want the projectile to spawn from. Nest it inside the character that fires.
Then find the SpawnPoint.
private Transform spawnPoint;
private int SPAWN_DISTANCE = 1;
void Awake()
{
spawnPoint = transform.Find("SpawnPoint");
}
Also make this change to your shooting.
void Shoot()
{
Rigidbody _projBody = Instantiate(projectile, spawnPoint.position + SPAWN_DISTANCE * transform.forward, transform.rotation) as Rigidbody;
_projBody.velocity = transform.TransformDirection(new Vector3(0, 0,speed));
}

Categories

Resources