Sfoglia il codice sorgente

implement player rotation

sl@cccfr.de 2 anni fa
parent
commit
98326539bf
8 ha cambiato i file con 213 aggiunte e 125 eliminazioni
  1. 10 8
      Main.gd
  2. 19 12
      Main.tscn
  3. 115 81
      Player.gd
  4. 24 0
      TextureLoader.gd
  5. 7 7
      TopoLoader.gd
  6. 18 10
      common.gd
  7. 19 6
      flat_tile.gd
  8. 1 1
      project.godot

+ 10 - 8
Main.gd

@@ -8,13 +8,13 @@ extends Spatial
 var Chunk = preload("res://chunk.tscn")
 
 var minlat = 0
-var maxlat = 10
+var maxlat = 1
 var minlon = 0
-var maxlon = 10
+var maxlon = 1
 var steplat = 1
 var steplon = 1
 
-var resolution = 256
+var resolution = 512
 var radius = 1737.4
 
 var curlat = 0
@@ -36,11 +36,7 @@ func _input(event):
 func _process(delta):
 	if curlat < maxlat*steplat:
 		if curlon < maxlon*steplon:
-			var chunk = Chunk.instance()
-			chunk.setParams(curlat,curlat+steplat,curlon,curlon+steplon,resolution,radius)
-			#moontile.scale=Vector3(1000,1000,1000)
-			$Tiles.add_child(chunk)
-			.get_node("UI/3").text="lastLatLon="+str(curlat)+":"+str(curlon)
+			call_deferred("add_chunk", curlon, curlat)
 			curlon += steplon
 		else:
 			curlat +=steplat
@@ -48,6 +44,12 @@ func _process(delta):
 			if curlat >= maxlat:
 				print("loading complete")
 
+func add_chunk(curlon, curlat):
+	var chunk = Chunk.instance()
+	chunk.setParams(curlat,curlat+steplat,curlon,curlon+steplon,resolution,radius)
+	#moontile.scale=Vector3(1000,1000,1000)
+	$Tiles.add_child(chunk)
+	.get_node("UI/3").text="lastLatLon="+str(curlat)+":"+str(curlon)
 
 # Called every frame. 'delta' is the elapsed time since the previous frame.
 #func _process(delta):

+ 19 - 12
Main.tscn

@@ -1,4 +1,4 @@
-[gd_scene load_steps=8 format=2]
+[gd_scene load_steps=9 format=2]
 
 [ext_resource path="res://Main.gd" type="Script" id=1]
 [ext_resource path="res://Player.gd" type="Script" id=2]
@@ -11,7 +11,9 @@ sun_energy = 4.66
 background_mode = 2
 background_sky = SubResource( 4 )
 
-[sub_resource type="SphereShape" id=3]
+[sub_resource type="CapsuleShape" id=8]
+
+[sub_resource type="CapsuleMesh" id=7]
 
 [sub_resource type="SpatialMaterial" id=6]
 albedo_color = Color( 0.168627, 0.164706, 0.913725, 1 )
@@ -21,7 +23,7 @@ material = SubResource( 6 )
 radius = 7.0
 height = 14.0
 
-[node name="Spatial" type="Spatial"]
+[node name="root" type="Spatial"]
 script = ExtResource( 1 )
 __meta__ = {
 "_edit_lock_": true
@@ -34,18 +36,26 @@ environment = SubResource( 2 )
 script = ExtResource( 2 )
 
 [node name="Camera" type="Camera" parent="Player"]
-
-[node name="SpotLight" type="SpotLight" parent="Player/Camera"]
-transform = Transform( 1, 0, 0, 0, 1, 0, 0, 0, 1, -0.00356923, 0.0967088, 0.161055 )
-light_energy = 7.3
+transform = Transform( 1, 0, 0, 0, 0.905309, 0.424753, 0, -0.424753, 0.905309, 0, 2.72781, 4.43474 )
 
 [node name="CollisionShape" type="CollisionShape" parent="Player"]
-shape = SubResource( 3 )
+transform = Transform( 1, 0, 0, 0, -4.37114e-08, -1, 0, 1, -4.37114e-08, 0, 0, 0 )
+shape = SubResource( 8 )
 
 [node name="OmniLight" type="OmniLight" parent="Player"]
-transform = Transform( 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.319878, -0.629829 )
+transform = Transform( 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.317136, 0.127762 )
+visible = false
 light_energy = 11.83
 
+[node name="MeshInstance" type="MeshInstance" parent="Player"]
+transform = Transform( 1, 0, 0, 0, -0.0140669, 0.999901, 0, -0.999901, -0.0140669, 0, 0, 0 )
+mesh = SubResource( 7 )
+material/0 = null
+
+[node name="SpotLight" type="SpotLight" parent="Player/MeshInstance"]
+transform = Transform( 1, 0, 0, 0, 0.573905, -0.818922, 0, 0.818922, 0.573905, -0.00356923, 0.433873, 1.27676 )
+light_energy = 7.3
+
 [node name="Tiles" type="Spatial" parent="."]
 __meta__ = {
 "_edit_lock_": true
@@ -93,9 +103,6 @@ margin_top = 47.0
 margin_right = 789.0
 margin_bottom = 87.0
 text = "4"
-__meta__ = {
-"_edit_use_anchors_": false
-}
 
 [node name="reference" type="MeshInstance" parent="."]
 visible = false

+ 115 - 81
Player.gd

@@ -1,101 +1,135 @@
-extends KinematicBody
-
-
-# physics
-var moveSpeed : float = 5.0
+#Johann Massyn, 23/06/2019
+#Godot (3.1) 3D Player movement script
 
-# cam look
-var minLookAngle : float = -90.0
-var maxLookAngle : float = 90.0
-var lookSensitivity : float = 10.0
+#Atatch script to 3d node with following structure
+#Kinematic body: Player
+#  - CollisionShape: CollisionShape
+#  - Camera: Camera
 
-var ray: RayCast
+extends KinematicBody
 
-# vectors
-var vel : Vector3 = Vector3()
-var mouseDelta : Vector2 = Vector2()
+export (bool) var can_move = true #Alow player to input movment.
+export (bool) var can_sprint = true #Alow player to toggle sprint movment.
+export (float) var move_speed = 8 #Players movement speed
+export (float) var move_speed_sprint = 16 #Players sprint movement speed
+export (bool) var move_sprint = false #Player sprinting toggle
+export (float) var move_acceleration = 7 #Players acceleration to movment speed 
+export (float) var move_deacceleration = 10 #Players deacceleration from movment speed
+export (bool) var mouse_captured = true #Toggles mouse captured mode
+export (float) var mouse_sensitivity_x = 0.3 #Mouse sensitivity X axis
+export (float) var mouse_sensitivity_y = 0.3 #Mouse sensitivity Y axis
+export (float) var mouse_max_up = 90 #Mouse max look angle up
+export (float) var mouse_max_down = -80 #Mouse max look angle down
+export (float) var Jump_speed = 6 #Players jumps speed
+export (bool) var allow_fall_input = true #Alow player to input movment when falling
+export (bool) var stop_on_slope = false #Toggle sliding on slopes
+export (float) var max_slides = 4 #Maximum of slides
+export (float) var floor_max_angle = 60 #Maximum slop angle player can traverse
+export (bool) var infinite_inertia = false #Toggle infinite inertia
+export (float) var gravaty = 1.625 #9.81 #Gravaty acceleration
+export (Vector3) var gravaty_vector = Vector3(0, -1, 0) #Gravaty normal direction vector
+export (Vector3) var floor_normal = Vector3(0, 1, 0) #Floor normal direction vector
+export (Vector3) var jump_vector = Vector3(0, 1, 0) #Jump normal direction vector
+export (Vector3) var velocity = Vector3(0, 0, 0) #Initial velocity
 
-onready var camera : Camera = get_node("Camera")
+onready var up = global_transform.origin.normalized()
+onready var forward = global_transform.basis.y
+onready var right = forward.cross(up).normalized()
 
 func _ready():
-	move_and_slide(Common.latLonToGlobal(0,0,1750), Vector3.UP)
-	ray = RayCast.new()
-	.get_parent().add_child(ray)
+	move_and_slide(Common.latLonToGlobal(Vector3(0,0,1750)), Vector3.UP)
+	if mouse_captured:
+		Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
+	pass
 
 func _process(delta):
-	# rotate the camera along the x axis
-	camera.rotation_degrees.x -= mouseDelta.y * lookSensitivity * delta
-	
-	# clamp camera x rotation axis
-	camera.rotation_degrees.x = clamp(camera.rotation_degrees.x, minLookAngle, maxLookAngle)
-	
-	# rotate the player along their y-axis
-	rotation_degrees.y -= mouseDelta.x * lookSensitivity * delta
-	
-	# reset the mouseDelta vector
-	mouseDelta = Vector2()
-	var origin = get_global_transform().origin
-	.get_parent().get_node("UI/2").text="latlonhight: "+str(Common.globalToLatLon(origin.x,origin.y,origin.z, origin.length()))+","+str(origin.length())
- 
-func _input(event):
-	if event is InputEventMouseMotion and Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
-		mouseDelta = event.relative
+	var pos = self.global_transform.origin
+	.get_parent().get_node("UI/1").text="x:%s y:%s z:%s" %[pos.x, pos.y, pos.z]
+	.get_parent().get_node("UI/2").text="latlonhight: "+str(Common.globalToLatLon(pos))+","+str(pos.length())
 
+	floor_normal = pos.normalized()
+	gravaty_vector = floor_normal * -1
+	#self.transform.basis.y = floor_normal
+	#rotation_degrees.x = 90
+	
 func _physics_process(delta):
- 
-	# reset the x and z velocity
-	vel.x = 0
-	vel.y = 0
-	vel.z = 0
 	
-	var input = Vector3()
+	#player movement XY
+	var dir = Vector3()
+	up = global_transform.origin.normalized()
+	right = forward.cross(up).normalized()
+	forward = up.cross(right).normalized()
 	
-	# movement inputs
-	if Input.is_action_pressed("move_forward"):
-		input.y -= 1
-	if Input.is_action_pressed("move_backward"):
-		input.y += 1
-	if Input.is_action_pressed("move_left"):
-		input.x -= 1
-	if Input.is_action_pressed("move_right"):
-		input.x += 1
-	if Input.is_action_pressed("move_up"):
-		input.z += 1
-	if Input.is_action_pressed("move_down"):
-		input.z -= 1
+	if can_move and (is_on_floor() or allow_fall_input):
+		
+		#Left
+		if Input.is_action_pressed("move_left"):
+			dir -= right
+			
+		#Right
+		if Input.is_action_pressed("move_right"):
+			dir += right
+			
+		#Forward
+		if Input.is_action_pressed("move_forward"):
+			dir += forward
 		
-	input = input.normalized()
+		#Backwards	
+		if Input.is_action_pressed("move_backward"):
+			dir -= forward
+			
+		# Jump
+		if not is_on_floor():
+			if Input.is_action_pressed("move_up"):
+				dir += up
+		if Input.is_action_pressed("move_down"):
+			dir -= up
+			
+		#Jump
+		#if Input.is_action_pressed("move_jump") and is_on_floor():
+		#	velocity += jump_vector * Jump_speed - (jump_vector * -1).normalized() * velocity.dot(jump_vector * -1)
 	
-	# get the forward and right directions
-	var forward = global_transform.basis.z
-	var right = global_transform.basis.x
-	var up = global_transform.basis.y
+		#Sprint toggle
+		if can_sprint and Input.is_action_just_pressed("move_sprint") and is_on_floor():
+			move_sprint = true
+			
+		if can_sprint and not Input.is_action_pressed("move_sprint") and is_on_floor():
+			move_sprint = false
+
+	velocity = velocity.linear_interpolate(dir * move_speed, move_acceleration * delta)
+	if !is_on_floor():
+		velocity += gravaty_vector * gravaty * delta
+	velocity = move_and_slide(velocity, up)
 	
-	var relativeDir = (forward * input.y + right * input.x + up * input.z)
+	transform = transform.looking_at(global_transform.origin + forward, up)
 	
-	var moveSpeed2 = moveSpeed
-	if Input.is_action_pressed("sprint"):
-		moveSpeed2 = moveSpeed * 3
-	# set the velocity
-	vel.x = relativeDir.x * moveSpeed2
-	vel.z = relativeDir.z * moveSpeed2
-	vel.y = relativeDir.y * moveSpeed2
 	
-	var gravity = self.global_transform.origin.normalized()
-	# move the player
-	vel = move_and_slide(vel, Vector3.UP)
-	#ray = ray.look_at(self.global_transform.origin, Vector3.UP)
+	#Smooth movement
+	#dir = transform.basis.xform(dir.normalized()) * (move_speed_sprint if move_sprint else move_speed)
+	#if is_on_floor() or dir != Vector3(0, 0, 0):
+	#	var acceleration = move_acceleration if dir.dot(velocity) else move_deacceleration
+	#	var vp = gravaty_vector.normalized() * velocity.dot(gravaty_vector)
+	#	velocity = (velocity - vp).linear_interpolate(dir, acceleration * delta) + vp
 	
-	var pos = self.global_transform.origin
-	var polPos = Common.globalToLatLon(pos.x,pos.y,pos.z)
-	var rotationDeg=get_rotation_degrees().x
-	var posNorm=abs(pos.normalized().y)
-	var targetRot = posNorm * 90
-	#if rotationDeg < targetRot:
-		#rotate_x(1)
-	#elif rotationDeg > targetRot:
-		#rotate_x(-1)
+	#Gravaty
+	#if !is_on_floor():
+	#	velocity += gravaty_vector * gravaty * delta
 	
-	.get_parent().get_node("UI/1").text="x:%s y:%s z:%s" %[pos.x, pos.y, pos.z]
-	#.get_node("UI/3").text="LatLonPos=="+str(latLonToGlobal( self.global_transform.origin.x,self.global_transform.origin.y))
+	#Player move
+	#move_and_slide(velocity, floor_normal, stop_on_slope, max_slides, deg2rad(floor_max_angle), infinite_inertia)
 	
+	#Player orientation
+	#var spos = Common.globalToLatLon(self.global_transform.origin)
+	#global_rotate(Vector3(1,0,0), deg2rad(spos.x))
+	#global_rotate(Vector3(0,1,0), deg2rad(spos.y))
+
+
+func _input(event):
+	#Mouse movement
+	if event is InputEventMouseMotion and Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
+		rotate_y(deg2rad(-event.relative.x * 0.3))
+		forward = forward.rotated(up, deg2rad(-event.relative.x * mouse_sensitivity_x))
+		#rotate_y(deg2rad(-event.relative.x * mouse_sensitivity_x))
+		#self.rotation_degrees.y += -event.relative.x * mouse_sensitivity_x
+		$Camera.rotation_degrees.x = clamp($Camera.rotation_degrees.x + -event.relative.y * mouse_sensitivity_y, mouse_max_down, mouse_max_up)
+	pass

+ 24 - 0
TextureLoader.gd

@@ -0,0 +1,24 @@
+extends Reference
+
+
+var filePrexif = "user://colorTiles"
+
+
+# Called when the node enters the scene tree for the first time.
+func _ready():
+	pass # Replace with function body.
+
+func loadTexture(lat, lon):
+	lat =int(lat)
+	lon = int(lon)
+	var texName = getTexName(lat, lon)
+	print(texName)
+	var tex = load(texName)
+	return tex
+	
+func getTexName(lat, lon):
+	return "%s/m-%s-%s.png" % [filePrexif, lat, lon]
+
+# Called every frame. 'delta' is the elapsed time since the previous frame.
+#func _process(delta):
+#	pass

+ 7 - 7
TopoLoader.gd

@@ -1,17 +1,17 @@
 extends Node
 
 
-var datafile = "user://SLDEM2015_256_60S_60N_000_360_FLOAT.IMG"
-var samplesPerLine = 92160
-var lines = 30720
+var datafile = "user://sldem2015_512_00n_30n_000_045_float.img"
+var samplesPerLine = 23040
+var lines = 15360
 var offset = 1737.4
 var scaleFact = 1
-var resolution = 256
+var resolution = 512
 
-var latMin = -60
-var latMax = 60
+var latMin = 0
+var latMax = 30
 var lonMin = 0
-var lonMax = 360
+var lonMax = 45
 
 var cache = {}
 var file: File

+ 18 - 10
common.gd

@@ -1,8 +1,10 @@
 extends Node
 
-
-func latLonToGlobal(latPos, lonPos, height=1737.4, offset:=Vector3(), origin:=Vector3()):
-	height = height + offset.z
+# spos.x = lat, spos.y=lon, spos.z=height
+func latLonToGlobal(spos: Vector3, offset:=Vector3(), origin:=Vector3()):
+	var height = spos.z + offset.z
+	var latPos = spos.x
+	var lonPos = spos.y
 	var lat = float(latPos+offset.x)*PI/180
 	var w = cos(lat)
 	var y = sin(lat)
@@ -11,14 +13,20 @@ func latLonToGlobal(latPos, lonPos, height=1737.4, offset:=Vector3(), origin:=Ve
 	var z = cos(lon)
 	return Vector3(x * height * w, y*height, z * height * w)-origin
 			
-func globalToLatLon(x, y, z, height=1737.4, offset=Vector3()):
+func globalToLatLon(pos: Vector3, offset=Vector3()):
+	var height=pos.length()
 	height = height + offset.z
 	var lon = 0
-	if z != 0: #and abs(x/z) < 1:
-		lon = atan(x/z)*180/PI
-	var lat = sign(y)*90
-	if abs(y) < height:
-		lat = asin(y/height)*180/PI
+	if pos.z != 0: #and abs(x/z) < 1:
+		lon = atan(pos.x/pos.z)*180/PI
+	var lat = sign(pos.y)*90
+	if abs(pos.y) < height:
+		lat = asin(pos.y/height)*180/PI
 	#print("x:"+str(x)+" y:"+str(y)+" z:"+str(z)))
 	#print("lat:"+str(lat)+" lon:"+str(lon))
-	return Vector2(lat, lon)
+	return Vector3(lat, lon, height)
+
+#func globalToRad(pos: Vector3):
+#	var floor_normal = pos - Vector3()
+#	floor_normal = floor_normal.normalized()
+#	floor_normal.basis.

+ 19 - 6
flat_tile.gd

@@ -2,6 +2,8 @@ extends MeshInstance
 
 var Point = preload("res://point.tscn")
 var TopoLoader = preload("res://TopoLoader.gd")
+var TextureLoader = preload("res://TextureLoader.gd")
+var grid = load("res://tex/grid.png")
 
 var latMin:float = 0
 var latMax:float = 1
@@ -43,8 +45,11 @@ func genMesh():
 	mesh = Mesh.new()
 	mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arr)
 	var mat = SpatialMaterial.new()
-	mat.albedo_color = Color(0.7,0.7,0.7,1)
+	#mat.albedo_color = Color(0.7,0.7,0.7,1)
+	var texl = TextureLoader.new()
+	mat.albedo_texture = texl.loadTexture(latMin, lonMin)
 	mesh.surface_set_material(0,mat)
+	.create_trimesh_collision()
 	
 	var drawBubbles = false
 	if drawBubbles:
@@ -72,11 +77,19 @@ func genNormals(verts:PoolVector3Array):
 func genUV():
 	var uvs = PoolVector2Array()
 	uvs.resize((resolution+1) * (resolution+1))
+	var v_idx = 0
+	for _y in range(0,resolution+1):
+		for _x in range(0,resolution+1):
+			var y = float(_y)
+			var x = float(_x)
+			var devider = float(resolution+1)
+			uvs[v_idx] = Vector2(x/devider,y/devider)
+			v_idx+=1
 	
-	for v_idx in range(0,(resolution+1) * (resolution+1)):
-		var y = v_idx / resolution
-		var x = v_idx % resolution
-		uvs[v_idx]=Vector2(clamp(x, 0, resolution),clamp(y, 0, resolution))
+	#for v_idx in range(0,(resolution+1) * (resolution+1)):
+	#	var y = v_idx / resolution
+	#	var x = v_idx % resolution
+	#	uvs[v_idx]=Vector2(clamp(x, 0, resolution),clamp(y, 0, resolution))
 	#print("uv")
 	#print(len(uvs))
 	return uvs
@@ -137,7 +150,7 @@ func convertToCartesian(verts:PoolVector3Array):
 	for vert in verts:
 		if not origin:
 			origin = vert			
-		carVerts[v_idx] = Common.latLonToGlobal(vert.x, vert.y, vert.z, Vector3())#, origin)
+		carVerts[v_idx] = Common.latLonToGlobal(vert, Vector3())#, origin)
 		v_idx+=1
 	#print("Cartesian")
 	#print(len(carVerts))

+ 1 - 1
project.godot

@@ -50,7 +50,7 @@ move_down={
 "events": [ Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":0,"alt":false,"shift":false,"control":false,"meta":false,"command":false,"pressed":false,"scancode":16777238,"physical_scancode":0,"unicode":0,"echo":false,"script":null)
  ]
 }
-sprint={
+move_sprint={
 "deadzone": 0.5,
 "events": [ Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":0,"alt":false,"shift":false,"control":false,"meta":false,"command":false,"pressed":false,"scancode":16777237,"physical_scancode":0,"unicode":0,"echo":false,"script":null)
  ]