Hallo
leider habe ich ein kleines Problem in Unity.
Und zwar habe ich ein Raumschiff, welches eine Bewaffnung hat.
Diese besteht aus einem Turm (welcher sich auf der y-Achse dreht) und
einem Geschütz-Objekt (welches sich auf der x-Achse drehen soll, also halt nach oben bzw. unten).
Beim Turm funktioniert das super.
Dafür habe ich folgenden Code benutzt:
|
C#-Quelltext
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
public float speed;
void FixedUpdate() {
// Generate a plane that intersects the transform's position with an upwards normal.
Plane playerPlane = new Plane(Vector3.up, transform.position);
// Generate a ray from the cursor position
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
// Determine the point where the cursor ray intersects the plane.
// This will be the point that the object must look towards to be looking at the mouse.
// Raycasting to a Plane object only gives us a distance, so we'll have to take the distance,
// then find the point along that ray that meets that distance. This will be the point
// to look at.
float hitdist = 0.0f;
// If the ray is parallel to the plane, Raycast will return false.
if (playerPlane.Raycast (ray, out hitdist))
{
// Get the point along the ray that hits the calculated distance.
Vector3 targetPoint = ray.GetPoint(hitdist);
// Determine the target rotation. This is the rotation if the transform looks at the target point.
Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
// Smoothly rotate towards the target point.
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, speed * Time.deltaTime);
}
}
|
Nochmal ohne die Kommentare zur Übersicht:
|
C#-Quelltext
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public float speed;
void FixedUpdate() {
Plane playerPlane = new Plane(Vector3.up, transform.position);
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
float hitdist = 0.0f;
if (playerPlane.Raycast (ray, out hitdist))
{
Vector3 targetPoint = ray.GetPoint(hitdist);
Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, speed * Time.deltaTime);
}
}
|
Nun dachte ich, ich könnte denselben Code leicht abgeändert auch für das Geschütz nutzen.
Schließlich soll ja dasselbe gemacht werden, also nur um eine andere Achse, weswegen ich
"Vector3.up" zu "Vector3.left" geändert habe.
Funktioniert aber nicht wirklich. Ich habe auch alle anderen Vector3.right/down/forward/back ausprobiert aber es funktioniert einfach nicht.
Ab einen bestimmten Punkt dreht sich das Geschütz dann einfach nicht nur nach oben oder unten,
sondern auch nach links oder rechts oder sonstwie, was aber nicht passieren soll.
Könnt ihr da den Fehler finden oder mir helfen, dass zum laufen zu bekommen.
Sitze da schon länger dran
Liebe Grüße,
Tobi