I've been doing some research on why my player(GameObject) is does not rotate toward my mouse position in my TopDown 3D game and I can't seem to find what is wrong with my code, so im making this post. The problem thats I have is that only the GameObject of my player (in my case, a capsule) rotate toward my mouse position but the axis of my player stays the same. In other word, I can't rotate the axis of my player, to face my mouse position, but I can rotate the GameObject of my player to face my mouse position. Its really hard to explain and this never happened to me before. Question is how can I rotate the axis of my player to face my mouse position. Keep in mind that my game is a top down view.
Here is the code im using for my playerMouvment and for my mouseLook:
public class Controller : MonoBehaviour
{
public float moveSpeed = 6;
Rigidbody rb;
Camera viewCamera;
Vector3 velocity;
void Start()
{
rb = GetComponent<Rigidbody>();
viewCamera = Camera.main;
}
void Update()
{
Vector3 mousePos = viewCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, viewCamera.transform.position.y));
transform.LookAt(mousePos + Vector3.up * transform.position.y);
velocity = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized * moveSpeed;
}
void FixedUpdate()
{
rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
}
}
Again I tried and look for any error in my code and I can't find anything that cause this weird situation and so if anyone can help me find a better way to write this code and solve my problem it would be great!
If I understand you correctly everything is fine with your game and the player is turning as it should, but only in the editor that the axis of the player (red, green and blue arrows) don't turn with the player?
If this is the problem it might be that you are using global space handle instead of local space. Clicking the icon I highlighted in the image should do the trick.
Use this code instead of LookAt() function
Vector2 direction = mousePos.position - player.transform.position;
player.transform.right /* Maybe you need Up or -Up or -right */ = direction;
This would work too in some cases
Vector2 direction = new Vector2
(
mousePos.position.x - player.transform.position.x,
mousePos.positoin.y - player.transform.position.y
)
player.transform.right /* Maybe you need Up or -Up or -right */ = direction;
Related
trying for 2 days to rotate a gun around a player in a 2d platfromer and i have 3 problems
1: the item or rotate uncontrolebly (my grammer isnt the best my mother language isnt even latin base)
around the player even if i dont move my mouse .or its rotate on its self like a wheel.
2:its seems phisycs some how work on the gun even though its dosnt has a rigibid body. givin in rb on kinimatic halped but not fully.
3: its rotate way to quickly . little movment will cause it to fly
4(bonus) the sqauer module i gave it strach and band in a really weird way.
heres the code:your text
[SerializeField] float fireRate = 0.3f;
[SerializeField] float rocketSpeed = 20f;
[SerializeField] GameObject rocketType;
[SerializeField] Transform firePoint;
Player player;
Vector3 mousePos;
Camera mainCam;
void Start()
{
player = FindObjectOfType<Player>();
mainCam = FindObjectOfType<Camera>().GetComponent<Camera>();
}
// Update is called once per frame
void Update()
{
mousePos = mainCam.ScreenToWorldPoint(Input.mousePosition);
}
private void FixedUpdate()
{
Vector3 aimDirection = mousePos - transform.position;
float aimAngle = Mathf.Atan2(aimDirection.y, aimDirection.x) * Mathf.Rad2Deg ;
// Quaternion rotation = Quaternion.AngleAxis(aimAngle, Vector3.forward);
// transform.rotation = rotation;
transform.rotation = Quaternion.Euler(0, 0, aimAngle);
// transform.RotateAround(player.transform.position, Vector3.forward, aimAngle);
}
here a picture of the componets:
enter image description here
wanted a gun obj to rotate around my charcter whan its move or still, wanted to shoot stuff while i jump.
Mathf.Atan2 returns the value in Radians, but Quaternion.Euler uses Degrees. You'll have to multiply the value by Mathf.Rad2Deg first.
It also sounds like the parent of the gun has a rigidbody which is causing it to Rotate. Remove the rigidbody you put on the gun and toggle on "Freeze Rotation" on the parent's rigidbody.
I am making something where the player is shot in opposite direction that they are looking. Like knockback from their weapon. This code works fine to launch up and down but when I try to make it launch the player horizontally, it just teleports to the side a little bit. When I was researching this, the only thing I saw with a similar problem was because of the animator, but I don't have an animator attached to the player.
[SerializeField] private Rigidbody PlayerBody;
[SerializeField] private float Lauchforce;
void Update()
{
//Walking
Vector3 MoveVector = transform.TransformDirection(PlayerMovementInput) * Speed;
PlayerBody.velocity = new Vector3(MoveVector.x, PlayerBody.velocity.y, MoveVector.z);
if (Input.GetMouseButtonDown(0))
{
Vector3 camDirection = Camera.main.transform.forward;
Vector3 LaunchVector = transform.TransformDirection(Camera.main.transform.forward);
PlayerBody.velocity = new Vector3(-LaunchVector.x, -LaunchVector.y, -LaunchVector.z); //just to change direction easily
PlayerBody.AddForce(-camDirection * Lauchforce, ForceMode.Impulse);
}
MovePlayerCamera();
}
The code for launching the player works fine. It's the code for walking that is stopping the player from being able to move on the x or z axis without using w a s d keys. The walking code changes the velocity on the x and z axis when the keys are pressed. This means that without the keys being pressed, it always wants to change the velocity to zero. That is why it teleports a little bit, the force is being applied, but the velocity changes back to zero on the next frame.
I am currently creating a game in Unity, in which you move a ball around using OnMouseDrag(), a CircleCollider2D and a RigidBody2D. This is how I set the position of the ball:
private void OnMouseDrag()
{
Vector2 mouseInWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
playerRb.position = new Vector3(mouseInWorld.x, mouseInWorld.y, 0);
}
I still want the ball to slide on collision while the mouse moves around. Is there a way to do this?
I have tried RigidBody2D.MovePosition(), but the ball jumped around from one point to another, and Raycasts but couldn't get that to work either.
EDIT:
This is what I've got now:
playerRb.velocity = new Vector3(mouseInWorld.x - playerRb.position.x, mouseInWorld.y - playerRb.position.y, 0);
Now the problem is, that the ball lags behind the mousePosition.
When you use RigidBody.MovePosition, you don't call the physics engine and so it ignores collisions. If you want collisions to happen you need to use RigidBody.Velocity instead.
Doing this change will require you to make some change to your code though because what you give to RigidBody.Velocity is a velocity and not a position so you will need to calculate the velocity required in x,y (and z if you are in 3d) to reach your destination.
I invite you to read the Unity page about velocity for more info
https://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html
Note: This will make the player/ball stick to collisions.
Modifying the velocity could cause the ball to bounce around unexpectedly when the ball collides with the wall. I would use a CircleCast for this, check if it hit anything, then use MovePosition accordingly:
float cursorDepth;
Rigidbody2D playerRb;
CircleCollider cc;
void Awake()
{
playerRb = GetComponent<Rigidbody2D>();
cc = GetComponent<CircleCollider>();
}
private void OnMouseDrag()
{
Vector2 mouseInWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 posToMouse = mouseInWorld - playerRb.position;
RaycastHit2D hit = Physics2D.CircleCast(playerRb.position,
cc.radius * transform.lossyScale.x, posToMouse, posToMouse.magnitude);
if (hit.collider != null)
{
mouseInWorld = hit.centroid;
}
playerRb.MovePosition(mouseInWorld);
}
But notice that if the ball can't move all the way to the mouse, it might cause the drag to end. So, plan accordingly.
I have a character/rigidbody and 'she' can turn around. When I press Play in Unity, if I move forward/backward, that's fine, she moves forward/backward. It's a good start.
But then if I turn her left or right, then go forward/backward, she now moves sideways.
She is a rigidbody component set as a parent in the scene.
Surely it's not difficult to do, but I can't figure out how to set her rotation so that when she turns, she will move 'forward' when I press the button to move her forward! There are plenty of first-person-shooter games where you can turn and move 'forward' and the player goes in the correct direction.
My rotation script at the moment is this:
Vector3 EulerAngleVelocity;
public float rotateSpeed = 250.0f;
void Update() {
if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.DownArrow))
{
MoveVector = PoolInput();
Move();
}
if (Input.GetKey(KeyCode.RightArrow))
{
EulerAngleVelocity = new Vector3(0, rotateSpeed, 0);
Quaternion deltaRotation = Quaternion.Euler(EulerAngleVelocity * Time.deltaTime);
rigidbody.MoveRotation(rigidbody.rotation * deltaRotation);
}
}
private void Move()
{
rigidbody.AddForce((MoveVector * moveSpeed));
}
private Vector3 PoolInput()
{
Vector3 dir = Vector3.zero;
dir.x = joystick.Horizontal();
dir.z = joystick.Vertical();
if (dir.magnitude > 1)
dir.Normalize();
return dir;
}
You're moving your joystick and adding that direction in relation to the WORLD instead of in relation to your player. If you want to add force relative to the orientation of the RigidBody probably what you want to use is rigidBody.AddRelativeForce (documentation) instead of simply rigidBody.AddForce.
Your problem isn't your rotation code, it's your movement code. You're applying a motion in world-space, not local-space ('object'-space).
For example, if you're using Vector3.Forward, you will want to use transform.Forward instead.
(For Unity 5.3.5f1)
Right now I am working on a 3D camera that is orbiting horizontally around the player. The player is a RigidBody rolling sphere. The player can freely rotate the axis horizontally but when there is no input I want the rotation to reset back to the direction of the velocity.
Right now all I need to know is how to situate the camera behind the player's direction of velocity by rotating the camera around the player from its previous rotation.
Here is a crude drawing of what I am looking for:
Currently to update the camera to orbit around the player I use this script on the camera (with comments):
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
public GameObject Player;
//I assume you would use this PlayerRB to find data regarding the movement or velocity of the player.
//public Rigidbody PlayerRB;
private float moveHorizontalCamera;
private Vector3 offset;
// Use this for initialization
void Start ()
{ //the offset of the camera to the player
offset = new Vector3(Player.transform.position.x - transform.position.x, transform.position.y - Player.transform.position.y, transform.position.z - Player.transform.position.z);
}
// Update is called once per frame
void Update ()
{
moveHorizontalCamera = Input.GetAxis("Joy X"); //"Joy X" is my right joystick moving left, none, or right resulting in -1, 0, or 1 respectively
//Copied this part from the web, so I half understand what it does.
offset = Quaternion.AngleAxis(moveHorizontalCamera, Vector3.up) * offset;
transform.position = Player.transform.position + offset;
transform.LookAt(Player.transform.position);
}
}
Any help at all would be great!
I would suggest you use Vector3.RotateTowards (https://docs.unity3d.com/ScriptReference/Vector3.RotateTowards.html)
You take the Vector that is currently pointing from the Player to the camera (transform.position - Player.transform.position) and rotate it towards -Player.GetComponent<Rigidbody>().velocity.normalized * desiredDistance (the vector pointing in the opposite direction of the players velocity with magnitude corresponding the desired distance of the camera to the player). You can then use Vector3.RotateTowards to rotate the camera (smoothly or immediately) around the Player by setting the cameras position accordingly.
Something like:
transform.position = Player.transform.position + Vector3.RotateTowards(transform.position - Player.transform.position, -Player.GetComponent<Rigidbody>().velocity.normalized * desiredDistance, step, .0f);
where step if the angle update in radians. (Note: you should avoid calling GetComponent<Rigidbody>() every Update. You are better off storing it somewhere)
I hope I understood your question correctly and this helps.