Raycast rotate help need in unity - unity3d

I have this code which lets an object rotate on Y axis. But I want to rotate the object on Z axis only. I tried to change the hPlane value, but no luck.
How can I do this?
Thanks
private Ray ray;
private Quaternion target;
private float speed = 1000.0f;
// Update is called once per frame
void Update () {
if (Input.GetMouseButton (0)) {
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
Plane hPlane = new Plane(Vector3.up, Vector3.zero);
float distance = 0;
if(hPlane.Raycast(ray, out distance)){
Vector3 targetPoint = ray.GetPoint(distance);
targetPoint += transform.position;
Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
float step = speed * Time.deltaTime;
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation,step);
}
}
}
Update:
My Goal is to rotate a bar (cube mesh) on Z axis smoothly using mouse click . The rotation will occur only when (this part I could not do) the mouse touch the corners of the bar.
I have already done the Z axis rotation with this code but the rotation very low (even for speed =1000.0f) and it rotates clockwise I suppose. But I want to move the bar in both direction and the movement will be smooth and faster like Quaternion.RotateTowards
Thanks
private Ray ray;
private RaycastHit hit;
private Quaternion target;
private float speed = 1000.0f;
// Update is called once per frame
void Update () {
if (Input.GetMouseButton (0)) {
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if(Physics.Raycast(ray, out hit)){
//transform.position = new Vector3(hit.point.x, hit.point.y, 0);
target = Quaternion.Euler(0.0f,0.0f, hit.point.z * speed);
transform.rotation = Quaternion.Slerp(transform.rotation, target, Time.deltaTime);
}
}
}
http://i.stack.imgur.com/7qIcs.jpg

I suggest you to change the orientation of the object axis. For a better use of the Quaternion functions, edit your bar in order to have local Y has rotation axis and local Z as look direction.
Then use this code :
if (Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Vector3 distance = hit.point - transform.position;
distance.y = 0;
Quaternion targetRotation = Quaternion.LookRotation(distance);
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, Time.deltaTime * speed);
}
}
Your bar will only rotate around Y axis.

Related

Unity2D - Enemy shoot at player in a cone shaped pattern

I am trying to set up an enemy that will shoot at the player in a cone shape/shotgun shape. If I set the projectile script to transform.position += transform.right * m_Speed * Time.deltaTime; then the cone shape works as intended, just only to the right and not in the direction of the player. With the current setup (below), the projectile will shoot at the player, but all the bullet prefabs will be on top of each other and all going in the same direction, not in a cone shape.
How can I adjust this so the enemy will shoot at the player but retain the cone shape?
Enemy Script
aimAngle = 60f;
for (int i = 0; i < spreadShot; i++)
{
var shotRotation = gameObject.transform.rotation;
shotRotation *= Quaternion.Euler(0, 0, aimAngle);
GameObject clone = Instantiate(projectile, new Vector2(gameObject.transform.position.x, gameObject.transform.position.y), shotRotation);
aimAngle = aimAngle - 30f;
Vector3 direction = (Vector3)((player.transform.position - transform.position));
direction.Normalize();
clone.GetComponent<Projectile>().Setup(direction);
}
Projectile.cs
[SerializeField] float m_Speed;
Vector3 shootDir;
public void Setup(Vector3 shootDir)
{
this.shootDir = shootDir;
}
private void Update()
{
transform.position += shootDir * m_Speed * Time.deltaTime;
}
Not perfect yet but here is a working solution if anyone else has the same question.
Enemy Script
[SerializeField] public float attackSpread;
[SerializeField] private float startShotTime;
[SerializeField] private float delayShotTime;
[HideInInspector] public int spreadShot;
public void Attack() {
Vector2 targetPosition = target.transform.position - aimIndicator.transform.position;
Vector2 dirTowardsTarget = (targetPosition - (Vector2)transform.position);
transform.right = targetPosition.normalized;
Quaternion newRot;
for (int i = 0; i < spreadShot; i++)
{
float addedOffset = (i - (spreadShot / 2)) * attackSpread;
newRot = Quaternion.Euler(transform.localEulerAngles.x,
transform.localEulerAngles.y,
transform.localEulerAngles.z + addedOffset);
Instantiate(projectile).GetComponent<ButcherProjectile>().SpawnBullet(transform.position, newRot);
}
}
Projectile Script
[SerializeField] private float MovementSpeed = 10;
private Vector2 velocity;
public void SpawnBullet(Vector3 position, Quaternion rotation)
{
transform.position = position;
transform.rotation = rotation;
velocity = transform.right.normalized * MovementSpeed;
}
public void Update()
{
Vector2 nextPosition = (Vector2)transform.position + (velocity * Time.deltaTime);
transform.position = nextPosition;
Destroy(gameObject, 2f);
}
At the moment, your code rotates the bullet itself, not the vector of direction towards player. Shot rotation you computed doesn't affect your direction in any way.
To elaborate, if you rotate an object and just move it by transform.position, you changed its position by exactly how you specified, as if you just changed its x, y or z component by hand. Your rotation change to an object would produce desired results if you used transform.Translate(params) as this operation is dependant on object's current rotation and scale.
Apply your rotation to the direction, it should work just fine :)
More reference on how to do it: https://answers.unity.com/questions/46770/rotate-a-vector3-direction.html

Keep camera from rotating around relative z-axis

I'm trying to create camera movement that mimics the behavior of the unity scene editor where you can perform a spherical rotation around the scene with 2d mouse movement. So far the camera is rotating correctly given x or y movement, but dragging diagonally causes the camera to rotate around its relative z-axis until it gets locked. I cannot force the camera to look at the origin relative to world up because then it cannot rotate upside-down
Here is the script that I've attached to the camera
using UnityEngine;
public class MainCamera : MonoBehaviour
{
Vector2 startingPosition;
Vector2 mousePosition;
Vector3 orthogonalCameraVector;
float degreesPerUnitWidth = 180f / Screen.width;
float degreesPerUnitHeight = 180f / Screen.height;
float cameraRadius = 10;
void Start()
{
transform.position = new Vector3(0, 0, -cameraRadius);
transform.LookAt(Vector3.zero);
orthogonalCameraVector = -Vector3.left;
}
void LateUpdate()
{
if (Input.GetMouseButtonDown(0))
{
mousePosition = Input.mousePosition;
}
if (Input.GetMouseButton(0))
{
var input = new Vector2(Input.mousePosition.x ,Input.mousePosition.y);
startingPosition = mousePosition;
var mouseDelta = startingPosition - input;
var xzDegrees = -mouseDelta.y * degreesPerUnitHeight;
var xzRotation = Quaternion.AngleAxis(xzDegrees, orthogonalCameraVector); // rotate about the relative x-z plane
var yRotation = Quaternion.AngleAxis(-mouseDelta.x * degreesPerUnitWidth, Vector3.up); // rotate about the world y-axis
var rotation = xzRotation * yRotation;
orthogonalCameraVector = rotation * orthogonalCameraVector;
transform.position = rotation * transform.position;
transform.rotation = rotation * transform.rotation;
mousePosition = Input.mousePosition;
}
}
}
I realized the orthogonalCamerVector only needed to be rotated about the y-axis because I wanted to keep it parallel with the xz-plane. I then applied this rotation to the orthogonalCamerVector before rotating the transform so it would always be rotating about a fixed plane so it looks something like this:
var xzDegrees = -mouseDelta.y * degreesPerUnitHeight;
var yRotation = Quaternion.AngleAxis(-mouseDelta.x * degreesPerUnitWidth, Vector3.up); // rotate about the world y-axis
orthogonalCameraVector = yRotation * orthogonalCameraVector;
var xzRotation = Quaternion.AngleAxis(xzDegrees, orthogonalCameraVector); // rotate about the relative x-z plane
var rotation = xzRotation * yRotation;
transform.position = rotation * transform.position;
transform.rotation = rotation * transform.rotation;

Angle information(degree) between AR camera and target object on a plane

I have a question, please help and thanks!
I want to know how to show the Angle information(degree) between AR camera and target object on a plane. (Using Smartphone)
And I want to know how to "code" with Unity and AR Foundation.
I tried using some code(below), but it seems only work on Distance, not work on Angle...
Thank again!
void Start ()
{
//get the components
private ARRaycastManager RayManager;
private GameObject visual;
public Camera CameraStart;
public Text textField2;
public Text textField;
float distance;
float angle;
RayManager = FindObjectOfType<ARRaycastManager>();
visual = transform.GetChild(0).gameObject;
}
void Update ()
{
// shoot a raycast from the center of the screen
List<ARRaycastHit> hits = new List<ARRaycastHit>();
RayManager.Raycast(new Vector2(Screen.width / 2, Screen.height / 2), hits, TrackableType.Planes);
RaycastHit hit;
//Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
// check if we hit an AR plane, update the position and rotation
if(hits.Count > 0)
{
transform.position = hits[0].pose.position;
transform.rotation = hits[0].pose.rotation;
distance = Vector3.Distance(CameraStart.transform.position, transform.position);
textField.text = distance.ToString("N2") + "meter";
Physics.Raycast(transform.position, out hit);
angle = Vector3.Angle(hit.normal, transform.forward);
textField2.text = angle.ToString("N2") + "degree";
if(!visual.activeInHierarchy)
visual.SetActive(true);
}
}
}
I would check that the ray hits:
if (Physics.Raycast(transform.position, out hit)) {
angle = Vector3.Angle(hit.normal, transform.forward);
textField2.text = angle.ToString("N2") + "degree";
} else {
Debug.LogError("Did not hit")
}
Also I would make sure that the target has a collider and that the layer mask is correct.

Rotate Camera vector to look at player Unity

I create a game, like minigolf/pool. I want to have a camera which follow player.
Position is normally ok, I get the ball direction and I lerp.
Rotation is almost ok. Currently, rotation by Y axis is ok, but camera look straigth forward, and don't look down to the player :
I already try many thing , quaternion angleToaxis, quarternion lookat ... but doesn't look good, the camera go look away ...
Here my code
namespace CameraManagerNameSpace
{
public class CameraManager : MonoBehaviour
{
public float cameraHeight=13f;
public PlayerNameSpace.Player playerToFollow;
public float followSpeed = 3f;
public float rotationSpeed = 1f;
float distance;
Vector3 position;
Vector3 newPos;
Quaternion rotation;
Quaternion newRot;
Vector3 playerPrevPos, playerMoveDir;
bool firstMoveDone=false;
void Start()
{
playerPrevPos = playerToFollow.player_transform.position;
distance = Vector3.Distance(transform.position,playerToFollow.player_transform.position);
}
void FixedUpdate()
{
if(Vector3.Distance(playerToFollow.player_transform.position ,playerPrevPos)>0.5f || firstMoveDone)
{
playerMoveDir = playerToFollow.player_transform.position - playerPrevPos;
firstMoveDone = true;
}
else
{
playerMoveDir = new Vector3(0,0,0);
}
if (playerMoveDir != Vector3.zero)
{
playerMoveDir.Normalize();
newPos = playerToFollow.player_transform.position - playerMoveDir * distance;
newRot =Quaternion.LookRotation(playerMoveDir,Vector3.up);
position = Vector3.Lerp(transform.position, new Vector3(newPos.x,newPos.y+cameraHeight,newPos.z), followSpeed * Time.deltaTime);
rotation = Quaternion.Lerp(transform.rotation, newRot, rotationSpeed * Time.deltaTime);
transform.position = position;
transform.rotation = rotation;
playerPrevPos = playerToFollow.player_transform.position;
}
}
}
}
Also, I don't know why, but after the balls stop the camera continue to do some movement very jerky, jolting, halting.
Well in
newRot = Quaternion.LookRotation(playerMoveDir,Vector3.up);
you are saying the camera to look in the same direction the player is moving ... not to look at the player. This would work if you wouldn't give the camera an extra position offset in the Y axis.
You might want to rather try
// vector pointing from the camera towards the player
var targetDirection = playerToFollow.player_transform.position - transform.position;
newRot = Quaternion.LookRotation(targetDirection, Vector3.up);
You should also rather use Update since FixedUpdate is only used for physics related stuff (also see Update & FixedUpdate)

unity camera follow rolling box

i have a cube that rolls with the arrow keys or control pad
up goes up, left turns left, and right turns right, so only the up makes it roll
im trying to get a camera to follow but not really getting anywhere
i found this script cant rember where that im trying to alter
but as i roll the cube forward the camera spins
simple video showing movment
https://imgur.com/a/BfoR1VF
any pointers in the right direction sorry about the pun would be good
simple lookat script
public Transform player;
void Start()
{
}
void Update()
{
Vector3 targetPostion = new Vector3(player.transform.position.x, transform.position.y,player.transform.position.z);
transform.LookAt(targetPostion);
}
and the follow script
// The target we are following
public Transform target;
// The distance in the x-z plane to the target
//So this would be your offset
public float distance = 10.0f;
// the height we want the camera to be above the target
public float height = 5.0f;
// How much we
public float heightDamping = 2.0f;
public float rotationDamping = 3.0f;
void LateUpdate()
{
// Early out if we don't have a target
if (!target) return;
// Calculate the current rotation angles
float wantedRotationAngle = target.eulerAngles.y;
float wantedHeight = target.position.y + height;
float currentRotationAngle = transform.eulerAngles.y;
float currentHeight = transform.position.y;
// Damp the rotation around the y-axis
currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);
// Damp the height
currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime);
// Convert the angle into a rotation
var currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);
// Set the position of the camera on the x-z plane to:
// distance meters behind the target
transform.position = target.position;
transform.position -= currentRotation * Vector3.forward * distance;
// Set the height of the camera
transform.position = new Vector3(transform.position.x, currentHeight, transform.position.z);
// Always look at the target
Vector3 thetargetPostition = new Vector3(0, target.position.y,0);
transform.LookAt(target.position);
//transform.LookAt(thetargetPostition);